javascript 指定したURLをタブで開く

javascript 指定したURLをタブで開く

javascriptで、指定したURLをタブで開くサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.134

指定したURLをタブで開く

指定したURLをタブで開くには、「window.open」で「_blank」を使用します。

<button onclick="foo()">button</button>

<script>

function foo(){
    window.open('https://mebee.info/', '_blank')
}

</script>

実行結果

ちなみに「window」オブジェクトは、省略することが可能です。

function foo(){
    open('https://mebee.info/', '_blank')
}

サンプルコード

以下は、
「実行」ボタンをクリックした際に、指定したURLを新しいタブで開くだけのサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="utf-8">
    <title>mebeeサンプル</title>
    <!-- MDB -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>

<body>

    <div class="container text-center w-75 mx-auto" style="margin-top:200px">

        <button type="button" onclick="hoge()" class="btn btn-raised btn-warning">
            取得
        </button>

    </div>

    <script>

        document.getElementsByClassName("btn")[0].addEventListener('click', () => {
            open('https://mebee.info/', '_blank')
        });

    </script>
</body>

</html>

実行結果を確認すると、タブで指定しているURLが開いていることが確認できます。