Chrome.extension.sendMessage inside chrome.tabs.create

I need to create a chrome extension that captures the currently visible tab and opens it in a new tab. I am using 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 have included receive.js like this:

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

      

The problem is that after creating a new tab ( newScreen.html first ) I could see the message Content loaded but not imagesrc >. Possibly because the onMessage.addEventListener is executed later (after sendMessage).

But if I click on my extension again and open the second newScreen.html , the previous newScreen.html gets the message and prints it out. If I open the third tab, the first and second tabs get the message again. The problem is that sendMessage gets executed even before the onMessageListener is added. I used TimeOut for sendMessage, but to no avail. Help me!

+3


source to share


1 answer


You say

Perhaps because it onMessage.addEventListener

is executed later (after sendMessage

).

And yes, it's true: you use a listener window.onload

to wait for the window to load, but the message is sent before the window is fully loaded . You should place your listener chrome.runtime.onMessage

from listener window.onload

like:

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 event handler window.onload

and make sure all the work is done when the window is loaded, for example:

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 need to place this receive.js

script on top of your markup inside the <head>

document, to make sure the listener is added as soon as it can:

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

      

+2


source







All Articles