如果在文档加载后运行,事件侦听器将接收空详细信息

Ain*_*aen 5 html javascript dom google-chrome-extension

我一直在为 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)

wOx*_*xOm 4

解决方法/修复方法是通过 JSON 简单地“清理”数据:

document.dispatchEvent(
  new CustomEvent('globalPasser',
    JSON.parse(JSON.stringify({
      detail: {
        variable: neededGlobalVariable
      }
    }))
  )
);
Run Code Online (Sandbox Code Playgroud)

这种情况下的问题是由数据中存在的 JS 函数引起的——有时——可能是当站点仍在处理某些内容时。DOM 节点也会导致同样的问题。

不管是有意还是无意,Chrome 都会中止序列化整个detail对象并将其传输为https://crbug.com/85158null ,并且这种行为与扩展消息传递奇怪地不同,扩展消息传递会跳过此类不可序列化的内容: 传输为.{foo: functionRef, bar: 123}{bar: 123}