更新时间:2023-12-05 09:17:58
时尚的chrome扩展名使用以下步骤解决了此问题:
Stylish chrome extension solved this problem using the following steps:
persistent:true
背景页面。可以说,在这种通信方案中,这是唯一避免非持久事件页面可靠地避免 FOUC 的方法需要一些时间来加载。< html>
下直接添加一个样式元素。"persistent": true
background page. Arguably, it's the only method to avoid FOUC reliably in this communication scenario as non-persistent event pages need some time to load.<html>
.在您的情况下,还需要执行其他步骤:
In your case an additional step is needed:
manifest.json:
manifest.json:
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"js": ["contents.js"]
"matches": ["<all_urls>"],
"run_at": "document_start",
"all_frames": true,
}
],
内容脚本:
var gotData = false;
chrome.runtime.sendMessage({action: 'whatDo'}, doSomething);
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action == 'doSomething') {
doSomething(msg);
}
});
function doSomething(msg) {
if (gotData || !msg || !msg.data)
return;
gotData = true;
new MutationObserver(onMutation).observe(document, {
childList: true, // report added/removed nodes
subtree: true, // observe any descendant elements
});
function onMutation(mutations, observer) {
// use the insanely fast getElementById instead of enumeration of all added nodes
var elem = document.getElementById('targetId');
if (!elem)
return;
// do something with elem
.............
// disconnect the observer if no longer needed
observer.disconnect();
}
}
背景页面脚本:
var state;
chrome.storage.sync.get({state: true}, function(data) {
state = data.state;
});
chrome.storage.onChanged.addListener(function(changes, namespace) {
if (namespace == 'sync' && 'state' in changes) {
state = changes.state.newValue;
}
});
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action == 'whatDo') {
sendResponse({action: 'doSomething', data: state});
}
});
chrome.webNavigation.onCommitted.addListener(function(navDetails) {
chrome.tabs.sendMessage(
navDetails.tabId,
{action: 'doSomething', data: state},
{frameId: navDetails.frameId}
);
});
重复消息传递,一个简单的示例,它不检查消息是否已处理:
Repeated messaging, a simple example that doesn't check if the message was processed:
chrome.webNavigation.onCommitted.addListener(function(navDetails) {
var repetitions = 10;
var delayMs = 10;
send();
function send() {
chrome.tabs.sendMessage(
navDetails.tabId,
{action: 'doSomething', data: state},
{frameId: navDetails.frameId}
);
if (--repetitions)
setTimeout(send, delayMs);
}
});