Chrome扩展程序消息传递 - 内容脚本到弹出框

时间:2014-07-29 03:55:18

标签: javascript html google-chrome google-chrome-extension

首先,代码:

contentscript.js (在网页上运行)

这是在init

上触发的主window.onload方法内部
// first ask data and fill global variables
function askData() {
    var booleanToReturn = false;

    chrome.runtime.sendMessage({
        data: "--secret-id--"
    }, function(response) {

        // no response
        if(!response || response === undefined) return;

        // data not loaded yet, wait for some time
        if (response.toString() === "wait") {
            setTimeout(askData, 500);
            return;
        }

        // else data is loaded
        // load the global variables
        loadData(response);

        booleanToReturn = true;
    });

    return booleanToReturn;
}


var returnValue = askData();
console.log(returnValue); // always false :(

HTMLjs.js (适用于从右上角的图标加载的扩展程序页面)

init之外的window.onload方法。

// first load DB and set DB_loaded to true
DB_load(function(){ // asynchronous
    DB_loaded = true;
});

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){

    if(message.data.toString() === "--secret-id--"){
        // if data is loaded
        if(DB_loaded){
            // give the data
            sendResponse(theMainData);
        }
        // data not loaded
        else{
            // ask to wait
            sendResponse("wait");
        }
    }
});

从这个页面判断 - https://developer.chrome.com/extensions/messaging - 我的方法应该有效。但事实并非如此。 contentscript.js始终收到undefined作为回复。但是如果我的扩展弹出框在此askData函数调用发生之前打开,那么contentscript.js将获取数据。但是,打开通讯弹出框的要求未列出here那我该怎么办?

此外,我想我应该告诉我,HTMLjs.js通过以下方式链接到弹出框html:

<script src="../JavaScript/HTMLjs.js"></script>

请帮我解决这个问题。

编辑:这是我正在讨论的Chrome扩展程序 - ProKeys - 请仔细阅读其说明,了解我要做的事情。实际上,早些时候我的contentscript.js处理了设置中的所有更改(源自弹出框),但这偏离了替换网页文本框上的用户片段的主要任务。因此,我将处理数据设置的所有内容从那里迁移到弹出框javascript文件。但现在,无论何时加载网页,contentscript.js都需要向弹出框发送一次性请求以获取所有用户片段和其他设置。这个一次性请求我试图在上面的代码中实现,但它不起作用。

另外,我正在使用chrome.storage.local

谢谢!

0 个答案:

没有答案
相关问题