无法使用 JavaScript 更新网站图标以使其旋转

Can't update favicon with JavaScript to make it rotate

我正在关注 how to animate favicon 上的博客。我没有让它工作,所以我把它分解成几个部分,得出的结论是我没有用生成的数据更新网站图标。

控制台告诉我未定义 favicon,分配失败。

<!doctype html>
<html lang="en">
<head>
  <base href="/">
  <!-- <link rel="icon" type="image/x-icon" href="favicon.ico"> -->
  <link rel="icon" type="image/png" href="" width=32px>
</head>

<script>
  window.onload = function () {
    const canvas = document.querySelector('canvas');
    const context = canvas.getContext('2d');
    if (!!context) {
      context.clearRect(0, 0, 32, 32);
      context.beginPath();
      context.moveTo(0, 0); context.lineTo(0, 32);
      context.moveTo(0, 0); context.lineTo(32, 32);
      context.stroke();
      const data = canvas.toDataURL("image/png");
      console.log(data);
      favicon.href = data;
    }
  };</script>

<body>
  <canvas width="32" height="32"></canvas>
  <app-root>Loading...</app-root>
</body>

</html>

我可以看到数据出现在控制台中(假设它是正确的信息垃圾)。但是,下一行无法执行。博客中没有关于如何定义 favicon 的任何内容,我想知道它是否仅在某些 browsers/plattforms 中可行?

它需要是对网站图标的引用 link:

<link id=favicon rel="icon" type="image/x-icon" href="favicon.ico">

在 javascript 中创建对它的引用:

const favicon = document.getElementById('favicon');