【问题标题】:Chrome.extension.sendMessage within chrome.tabs.createchrome.tabs.create 中的 Chrome.extension.sendMessage
【发布时间】:2014-12-14 06:08:16
【问题描述】:

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

send.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);
    });
});

问题是,一旦创建了新标签(第一个 newScreen.html )我可以看到 Contents Loaded 消息,但看不到 imagesrc。可能是因为 onMessage.addEventListener 稍后执行(在 sendMessage 之后)。

但是,如果我再次单击我的扩展程序并打开第二个 newScreen.html ,则之前的 newScreen.html 会收到消息并打印出来。如果我打开第三个选项卡,则第一个和第二个选项卡会再次收到消息。问题是 sendMessage 甚至在添加 onMessageListener 之前执行。我将 TimeOut 用于 sendMessage 但徒劳无功。帮帮我!

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension sendmessage


    【解决方案1】:

    你说的是

    可能是因为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>
    

    【讨论】:

    • 谢谢!它奏效了.. :) 我尝试了所有可能的事件,终于成功了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2015-02-05
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多