简体   繁体   中英

Chrome.extension.sendMessage within chrome.tabs.create

I need to create a chrome extension which captures the current visible tab and open it in a new tab. I use the following code:

send.js

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

And inside newScreen.html I had included receive.js as follows:

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

The problem is, once the new tab is created(first newScreen.html ) I could see Contents Loaded message, but not the imagesrc . Maybe because the onMessage.addEventListener is executed later(after sendMessage).

But if I click my extension again and it opens the 2nd newScreen.html , the previous newScreen.html receives the message and prints it. If I open a third tab, the first and second tabs are receiving the message again. The problem is sendMessage executes even before onMessageListener is added. I used TimeOut for sendMessage but in vain. Help me out!

You're saying

Maybe because the onMessage.addEventListener is executed later (after sendMessage ).

And yes, that's true: you're using the window.onload listener to wait until the window loads, but the message is sent before the window loads completely . You should place your chrome.runtime.onMessage listener out of the window.onload listener, like this:

chrome.runtime.onMessage.addListener(function(request,sender,response) {
    console.log(request.someParam);
});

window.addEventListener("load",function(){
    console.log('contents Loaded');
});

If you want, you can store the request in some global variable, so that you can use it inside the window.onload event handler and make sure all the work is done when the window has been loaded, like this:

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

Obviously, you'll need to put this receive.js script on top of your markup, inside the <head> of the document, to make sure that the listener is added as soon as it can:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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