Chrome.extension.sendMessage within chrome.tabs.create

Chrome.extension.sendMessage within chrome.tabs.create

本文关键字:tabs create chrome within extension sendMessage Chrome      更新时间:2023-09-26

我需要创建一个 chrome 扩展程序来捕获当前可见的选项卡并在新选项卡中打开它。我使用以下代码:

发送.js

    function openNextPage(imagesrc) {  
   chrome.tabs.create({url: "newScreen.html"},function(tab){  
        chrome.runtime.sendMessage({someParam: imagesrc},function(response){console.log(response);});
    }  
  );    
}

newScreen中.html我包含了receive.js如下所示:

window.addEventListener("load",function(){
    console.log('contents Loaded');
    chrome.runtime.onMessage.addListener(function(request,sender,response) {
        console.log(request.someParam);
    });
});

问题是,一旦创建了新选项卡(第一个新屏幕.html),我可以看到内容加载消息,但看不到图像rc。也许是因为onMessage.addEventListener稍后执行(在sendMessage之后)。

但是,如果我再次单击我的扩展程序并打开第二个新屏幕.html,上一个新屏幕.html会收到消息并打印它。如果我打开第三个选项卡,第一个和第二个选项卡将再次收到消息。问题是sendMessage甚至在添加onMessageListener之前就执行了。我使用超时发送消息,但徒劳无功。帮帮我!

你是说

也许是因为onMessage.addEventListener稍后执行(sendMessage之后)。

是的,这是真的:您正在使用window.onload侦听器等待窗口加载,但消息是在窗口完全加载之前发送的。您应该将chrome.runtime.onMessage侦听器从window.onload侦听器中移出,如下所示:

chrome.runtime.onMessage.addListener(function(request,sender,response) {
    console.log(request.someParam);
});
window.addEventListener("load",function(){
    console.log('contents Loaded');
});

如果需要,可以将请求存储在某个全局变量中,以便可以在 window.onload 事件处理程序中使用它,并确保在加载窗口时完成所有工作,如下所示:

var MY_PARAMETER;
chrome.runtime.onMessage.addListener(function(request,sender,response) {
    MY_PARAMETER = request.someParam;
});
window.addEventListener("load",function(){
    // Now you are sure that the window is loaded
    // and you can use the MY_PARAMETER variable
    console.log("Contents loaded, MY_PARAMETER =", MY_PARAMETER);
});

显然,您需要将此receive.js脚本放在标记的顶部,在文档的<head>内,以确保尽快添加侦听器:

<html>
    <head>
        ...
        <script src="/path/to/request.js"></script>
        ...
    </head>
...
</html>