简体   繁体   中英

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

I want to run a callback function from content script after tab loading new page .

Here is my code :

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

I also uploaded the source code to google drive, you can download it using the bellow link : https://drive.google.com/open?id=15zSn40z4zYkvCZ8B-gclzixvy6b0C8Zr

as you can see the alert test don't show !

However if I remove the code which open new url , then alert ("test") appear !

I am not sure why ! but it looks like javascript lost the reference to the call back function when I open new url .

How can I solve the problem ? what's the correct way ?

Thank you

  1. The sendResponse function becomes invalid after the message callback returns, unless you return true from the event listener to indicate you wish to send a response asynchronously. ( https://developer.chrome.com/extensions/runtime#event-onMessage )

    Add return true; in background.js to make this handler asynchronous.

  2. Now you get an error Attempting to use a disconnected port object in the sendResponse(); call of background.js, and yes, that's a result of the page navigating away and losing the context that the content script was running in.

    There's no way to make this work: The context in which you wanted to call alert() simply doesn't exist anymore.

    Try using chrome.tabs.sendMessage instead. But this means you have to set up the listener at the top level, and not inside of any callback. Message passing is hard.

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