这是我第一次创建 Google Chrome 扩展程序,我无法找到一种方法来可靠地让内容脚本在单击 YouTube 上的建议视频或任何相关视频时运行一次。我尝试将“all_frames”设置为 true,但这会多次调用脚本。浏览 YouTube 视频时,是否有一种简单的方法可以让每个视频仅运行一次内容脚本?
PS:我使用 YouTube 作为主要示例,但其他网站上也存在此问题。是什么原因造成的以及如何修复它?
{//manifest.json
"name": "Test",
"version": "0.0.1",
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["run.js"],
}],
"permissions": ["activeTab"],
"manifest_version": 3
}
-
//run.js
console.log('running');
问题是 YouTube 动态更新页面,因此内容脚本并不总是在页面内容更改后运行。
您需要检测页面 url 是否已更改。
有两种方法可以检测内容变化。
Solution
- Use chrome.webNavigation.onHistoryStateUpdated https://developer.chrome.com/extensions/webNavigation事件来检测内容已更改。
您需要在中设置 webNavigation 的权限清单.json:
"permissions": [
*"tabs", "webNavigation"*
]
背景.js
chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
//Send message to content Script -> Page was changed
//or execute parser from here
// chrome.tabs.executeScript
});
内容.js// 解析你的内容
-
使用突变观察者: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver在您的内容脚本中。
MutationObserver 接口提供了监视 DOM 树所做更改的能力。
// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
// do something with content
}
else if (mutation.type == 'subtree') {
// do something with content
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)