Chrome: message content-script on runtime.onInstalled

假如想象 提交于 2019-12-25 01:53:28

问题


I'm the maker of an addon called BeautifyTumblr which changes the apperance of Tumblr. I wish for my Chrome extension to automatically detect when it has been updated and display changelog to the user. I use an event page with the chrome.runtime.onInstalled.addListener hook to detect when an update has occured, retrieve the changelog from a text file in the extension.. this all works fine, then when I want to forward it to my content script via chrome.tabs.sendmessage it just wont work, nothing ever happens, no errors no nothing. I'm stumped.

Any help would be much appreciated!

Event Page:

chrome.runtime.onInstalled.addListener(function (details) {
    "use strict";
    if (details.reason === "install") {

    } else if (details.reason === "update") {
        var thisVersion = chrome.runtime.getManifest().version, xmlDom, xmlhttp;
        xmlDom = null;
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", chrome.extension.getURL("changelog.txt"), false);
        xmlhttp.send(null);
        xmlDom = xmlhttp.responseText;
        chrome.tabs.query({'url' : 'http://www.tumblr.com/*'}, function (tabs) {
            if (tabs.length > 0) {
                var mTab = tabs[0].id;
                chrome.tabs.update(mTab, {active: true});
                setTimeout(chrome.tabs.sendMessage(mTab, {beautifyTumblrUpdate: xmlDom}), 500);
            } else {
                chrome.tabs.create({'url' : 'http://www.tumblr.com/dashboard'}, function (tab) {
                    setTimeout(chrome.tabs.sendMessage(tab.id, {beautifyTumblrUpdate: xmlDom}), 500);
                });
            }
        });
    }
});

Relevant code in Content Script:

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        "use strict";
        window.alert('test');
        if (request.beautifyTumblrUpdate) {
            window.alert(request.beautifyTumblrUpdate);
        } else if (request.beautifyTumblrInstall) {
            window.alert(request.beautifyTumblrInstall);
        }
    }
);

回答1:


I am also seeing the same thing. I am not a 100% sure but I think this happens because chrome shuts off connection between background page and "old" content scripts the moment the extension is updated. There's more info here in this bug : https://code.google.com/p/chromium/issues/detail?id=168263




回答2:


simple, use the following code in background,

chrome.runtime.onInstalled.addListener(function(details){
if(details.reason == "install"){
chrome.tabs.create({ url: chrome.extension.getURL('welcome.html')});  
}

});


来源:https://stackoverflow.com/questions/16454050/chrome-message-content-script-on-runtime-oninstalled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!