javascript faviconを変更する

javascript faviconを変更する

javascriptで、faviconを変更するサンプルコードを記述してます。

環境

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

favicon変更

他の要素と同様に、属性に値を指定すれば「favicon」を変更することが可能です。

<link id="fa" rel="SHORTCUT ICON" href="favicon.ico" type="image/vnd.microsoft.icon">

<script>

document.getElementById("fa").href="favicon2.ico";

</script>

存在しない要素を指定するとエラーになります。

<link id="fa" rel="SHORTCUT ICON" href="favicon.ico" type="image/vnd.microsoft.icon">

<script>

document.getElementById("xxx").href="favicon2.ico";
// Uncaught TypeError: Cannot set properties of null (setting 'href')

</script>

なので、存在チェックをしておきます。

if(document.getElementById("xxx") !== null){

    document.getElementById("xxx").href="favicon2.ico";

}

サンプルコード

以下は、
「変更」ボタンをクリックすると「favicon」を変更する
サンプルコードとなります。

※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。関数はアロー関数を使用してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link id="fa" rel="SHORTCUT ICON" href="" type="image/vnd.microsoft.icon">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 30px;
  }
</style>
<script>

  const hoge = () => {    
   
    fa.href="https://mebee.info/wp-content/uploads/favicon.ico";

  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
  }

</script>

<body>
  <div class="main">

    <button id="btn" type="button" class="btn btn-info">
      取得
    </button>

  </div>
</body>

</html>

「favicon」が変更されていることが確認できます。