我一直在为 Chrome 开发一个扩展。
为了工作,它必须使用 CustomEvent 将网站设置的全局窗口变量传递到扩展的主脚本。
当页面加载到活动选项卡中时,这通常可以正常工作,但是每当将其作为非焦点选项卡加载时,或者当扩展脚本的执行因其他原因而延迟时,侦听器接收到的事件对象都具有null
详细信息属性。
需要明确的是,事件的整个详细对象是null
,而不仅仅是所需的变量。我已经通过将所需的变量作为 JSON 字符串附加到文档来解决此问题,但我想了解该事件出了什么问题。
相关部分代码如下。
清单.json:
"content_scripts": [ {
"js": [ "main.js", "jquery-3.3.1.js"],
"matches": [ "*://*.site.com/*"],
"run_at": "document_end"
} ],
"permissions": [ "declarativeContent", "activeTab", "storage", "*://*.site.com/*" ],
"web_accessible_resources": [ "injectedScript.js" ]
Run Code Online (Sandbox Code Playgroud)
main.js:
$(function() {
document.addEventListener('globalPasser', function(response) {
if(response.detail){
// store variables
}
}, true);
var passGlobals = document.createElement('script');
passGlobals.src = chrome.extension.getURL('injectedScript.js');
(document.head||document.documentElement).appendChild(passGlobals);
passGlobals.onload = function() {
passGlobals.remove();
};
}
Run Code Online (Sandbox Code Playgroud)
注入脚本.js:
var newEvent = new CustomEvent('globalPasser', {detail:{variable: neededGlobalVariable}});
document.dispatchEvent(newEvent);
Run Code Online (Sandbox Code Playgroud)