启动时将消息从后台脚本发送到内容脚本

时间:2018-12-24 03:37:55

标签: javascript google-chrome-extension

我当前正在尝试在启动时(即在点击扩展程序图标之前)将消息从后台脚本传递到内容脚本

我尝试了以下方法(受https://stackoverflow.com/a/23895822/10500893的启发),但似乎没有用。

background.js

function preloadPopupScript(){
    return new Promise(function(resolve, reject){
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
            chrome.tabs.executeScript(tabs[0].id, {file: "popup.js"}, 
function(){
                if(chrome.runtime.lastError){
                    reject(Error("could not preload popup.js :("));
                }else{
                    resolve();
                }
            });
        });
    });
}

chrome.runtime.onStartup.addListener(function(){
    let preloadScript = preloadPopupScript();
    preloadScript.then(function(){

        let lastXHRresponse = chrome.storage.local.get("xhrResponse", 
function(d){
            if(chrome.runtime.lastError){
                console.log("could not find past authentication data!");
                return;
            }

            // GETS TO HERE
            chrome.runtime.sendMessage({status: "hasPreviouslyLoggedIn"});
            checkAccessToken();
            chrome.runtime.sendMessage({status: "checkArtistReleases"});
        });
    });
});

popup.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    switch(request.status){

        // THE BELOW CASE DOES NOT SHOW ANY SIGNS OF GETTING TRIGGERED
        case "hasPreviouslyLoggedIn":
        case "successfulLogin":
            chrome.browserAction.setPopup({popup: "login_signedin.html"});
            window.location.href = "login_signedin.html";
            hasSignedIn = true;
            chrome.runtime.sendMessage({action: "canCreateAlarm"});
            break;
    }
});

此代码是否存在任何问题,或者我在https://stackoverflow.com/a/23895822/10500893中未正确实施建议的解决方案?

提前非常感谢!

(还要为新手样式问题事先致歉,因为我刚刚选择了JS>。<)

0 个答案:

没有答案