繁体   English   中英

内容脚本只运行一次(临时插件)

[英]Content script only runs once (temporary addon)

我做了一个简单的临时插件:

manifest.json

{

  "manifest_version": 2,
  "name": "Content script test",
  "version": "1.0",

  "description": "TEST",

  "content_scripts": [
    {
      "matches": ["*://*.telex.hu/*"],
      "js": ["content-script.js"]
    }
  ]

}

内容脚本.js

console.log("*** Content script is running for " + document.location.href);

window.addEventListener(
        'load',
        function(){ console.log("*** Hello World!"); },
        true
    );

我在 FireFox 和 Chrome 上对其进行了测试。

当我打开一个新的浏览器选项卡并加载页面时,例如https://telex.hu ,然后我的插件运行正常(我在开发人员控制台中看到了日志)。 如果我右键单击页面上的链接,则所选页面(同一域)会在新选项卡中打开,并且插件可以正常运行。 但是,如果我左键单击一个链接并在同一选项卡中打开所选页面(同一域),那么什么也不会发生 - 插件不会运行(控制台上没有显示日志)...

解释是什么? 我应该怎么做才能使插件在每种情况下都运行???

解决方案是:

内容脚本.js

let lastUrl = location.href; 
new MutationObserver(() => {
  const url = location.href;
  if (url !== lastUrl) {
    lastUrl = url;
    onUrlChange();
  }
}).observe(document, {subtree: true, childList: true});

function onUrlChange() {
  console.log('*** URL changed!', location.href);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM