[英]Content script only runs once (temporary addon)
I made a simple temporary addon:我做了一个简单的临时插件:
manifest.json manifest.json
{
"manifest_version": 2,
"name": "Content script test",
"version": "1.0",
"description": "TEST",
"content_scripts": [
{
"matches": ["*://*.telex.hu/*"],
"js": ["content-script.js"]
}
]
}
content-script.js内容脚本.js
console.log("*** Content script is running for " + document.location.href);
window.addEventListener(
'load',
function(){ console.log("*** Hello World!"); },
true
);
I tested it on FireFox and Chrome.我在 FireFox 和 Chrome 上对其进行了测试。
When I open a new browser tab, and load in a page, for example https://telex.hu , then my addon runs correctly (I see the logs in the developers console).当我打开一个新的浏览器选项卡并加载页面时,例如https://telex.hu ,然后我的插件运行正常(我在开发人员控制台中看到了日志)。 If I right-click a link on the page then the selected page (same domain) opens in a new tab and the addon runs correctly.如果我右键单击页面上的链接,则所选页面(同一域)会在新选项卡中打开,并且插件可以正常运行。 But if I left-click a link and open the selected page (same domain) in the same tab, then nothing happens - the addon doesn't run (no log shows up on the console)...但是,如果我左键单击一个链接并在同一选项卡中打开所选页面(同一域),那么什么也不会发生 - 插件不会运行(控制台上没有显示日志)...
What is the explanation?解释是什么? And what should I do to make the addon run every case???我应该怎么做才能使插件在每种情况下都运行???
The solution is:解决方案是:
content-script.js内容脚本.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.