繁体   English   中英

加载页面后如何从内容脚本运行回调函数? 镀铬扩展

[英]How to run callback function from content script after loading page ? chrome extension

我想在标签加载新页面后从内容脚本运行回调函数。

这是我的代码:

content_script.js

chrome.runtime.onMessage.addListener(function(request, sender, callback) {
    if (request.id == "content_script") {
        // open google.com
        chrome.runtime.sendMessage({
            "id" : "openUrl",
            "url" : "https://google.com"
        }, function(response) {
        });
        // call background script
        // go to the claim code page
        chrome.runtime.sendMessage({
            "id" : "background"
        }, function() {
            alert("test");
        });
    }
});

background.js

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
    if (msg.id == "openUrl") {
        var tabId = sender.tab.id;
        var url = msg.url;
        openUrl(tabId, url);

    } else if (msg.id == "background") {
        setTimeout(function() {
            sendResponse();
        }, 5000);
    }

});

function openUrl(tabId, url) {
    chrome.tabs.update(tabId, {
        url : url,
        active : false
    }, function() {
        console.log("open tab url callback");
    });
};

我也将源代码上传到了Google驱动器,您可以使用以下链接下载它: https : //drive.google.com/open? id = 15zSn40z4zYkvCZ8B-gclzixvy6b0C8Zr

如您所见,警报测试未显示!

但是,如果我删除了打开新网址的代码,则会出现警报(“测试”)!

我不确定为什么! 但是当我打开新的url时,javascript似乎丢失了对回调函数的引用。

我该如何解决这个问题? 正确的方法是什么?

谢谢

  1. 消息回调返回之后, sendResponse函数将变为无效, 除非您从事件侦听器返回true表示您希望异步发送响应。 https://developer.chrome.com/extensions/runtime#event-onMessage

    添加return true; 在background.js中使该处理程序异步。

  2. 现在,您将收到一个错误消息, Attempting to use a disconnected port objectsendResponse(); Attempting to use a disconnected port object sendResponse(); 是对background.js的调用,是的,这是页面导航离开并丢失了内容脚本正在其中运行的上下文的结果。

    没有办法使它起作用:您要在其中调用alert()的上下文已经不存在了。

    尝试改用chrome.tabs.sendMessage 但这意味着您必须在顶层而不是任何回调内部设置侦听器。 消息传递很难。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM