微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用browser.tabs.executeScript加载时在tab上执行的内容脚本不会触发window.onload事件

如何解决使用browser.tabs.executeScript加载时在tab上执行的内容脚本不会触发window.onload事件

后台脚本的firefox扩展中,我们正在检查当前正在加载的标签,并检查该URL是否是我们所需的URL(如果它是我们所需的URL),那么我们将在浏览器的帮助下在该标签上执行一个javascript文件。使用browser.tabs.executeScript的tabs.onupdated事件,并且文件已成功执行,但内容脚本上出现的window.onload事件未执行 但是在内容脚本中执行的第一行的console语句

Background.js

 browser.tabs.onUpdated.addListener(
    function (tabId,changeInfo,tab) {
        // here checking wether to execute the script for the currently loading tab based on the URL of tab
        browser.tabs.executeScript(tab.id,{ file: "jquery.min.js" });
         browser.tabs.executeScript(tab.id,{ file: "automate.js" });
      
    },{ properties: ["status"] }
  );

automate.js

console.log("automate.js executing");
window.addEventListener("load",function(){
// this console.log statement not printed
 console.log("window is loaded");
})

解决方法

默认内容脚本为run at document_idle

文档及其所有资源均已加载完毕。

解决方案:

它与load事件条件相同,因此您不需要它。只需立即执行您需要的操作即可。

替代:

如果出于某种原因需要在load事件之前执行某些操作,然后再执行某些操作,则可以使用document_endDOMContentLoaded事件上运行脚本(DOM已准备好,资源仍在加载)或document_start(DOM为空,仅解析<html>节点)。

browser.tabs.executeScript(tab.id,{ file: 'jquery.min.js',runAt: 'document_end' });
browser.tabs.executeScript(tab.id,{ file: 'automate.js',runAt: 'document_end' });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。