Web扩展 - document.getElementById在执行异步方法之前返回null

时间:2018-04-20 14:28:37

标签: javascript html google-chrome-extension getelementbyid firefox-webextensions

我有一个chrome / firefox网络扩展程序。单击时,此Web扩展将DIV(包含嵌套结构中的其他几个DIV和iFrame)附加到网站HTML文件中<body>元素的内部。它通过使用内容脚本来实现。

以下是内容脚本中onMessage侦听器的简化代码:

    browser.runtime.onMessage.addListener((message) => {

    var iFrame = document.createElement("iFrame");
    iFrame.id = "contentFrame";
    iFrame.style.cssText = "width: 100%; height: 100%; border: none;";
    iFrame.src = browser.extension.getURL("inject.html");

    var boxDiv = document.createElement("div");
    boxDiv.style.cssText = "background: white; box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 9px 8px; height: 100%; left: calc(100% - 390px); position: fixed; top: 0px; width: 390px; z-index: 1;"

    var zeroDiv = document.createElement("div");
    zeroDiv.style.cssText = "position: fixed; width: 0px; height: 0px; top: 0px; left: 0px; z-index: 2147483647;";

    var outerDiv = document.createElement("div");

    boxDiv.appendChild(iFrame);
    zeroDiv.appendChild(boxDiv);
    outerDiv.appendChild(zeroDiv);
    document.body.appendChild(outerDiv);

    var closeButton1 = document.getElementById("contentFrame").contentWindow.document.getElementById("close-btn");
    console.log("Close Button1 Fetched: " + closeButton1);

    //closeButton.onClick = function () {
    //  console.log("Close button clicked");
    //}

    returnSummary(message.summaryLength, message.targetURL).then(summary => {

        var closeButton2 = document.getElementById("contentFrame").contentWindow.document.getElementById("close-btn");
        console.log("Close Button2 Fetched, Setting Listener: " + closeButton2);

        closeButton2.onClick = function() {
            console.log("Close button clicked");
        }
    });
});

对于上下文 - returnSummary是一个包含一堆获取请求的异步函数。

奇怪的部分如下:

第一个日志语句:console.log("Close Button1 Fetched: " + closeButton1);返回null

但第二个日志语句:console.log("Close Button2 Fetched, Setting Listener: " + closeButton2);返回[object HTMLButtonElement]

因此,document.getElementbyId似乎在异步请求完成后正在工作。为什么会发生这种情况,如何尽早检索ID为close-btn的HTML元素的值? (我想在按钮上设置一个onClick监听器)。

另一个奇怪的问题是,即使我设置对象onClick的{​​{1}}方法,点击“关闭按钮”也不会做任何事情。但是,这不是这篇文章的主要问题。

此处还有“inject.html”中的HTML,(顶部主要是CSS):

closeButton2

1 个答案:

答案 0 :(得分:1)

The reason you are not able to access the element is that iframe loading is an asynchronous process. Therefore you can use something like :

iframe.onload = function() { // do something here ; }

Another way is to use polling till the element gets loaded, obviously you'll need to add a timeout check there. This is especially useful when you are dealing with external DOM and you're unsure when is it going to load.

相关问题