将数据数组从一个chrome扩展环境传递到另一个

时间:2015-07-02 13:06:14

标签: google-chrome-extension google-chrome-devtools chrome-runtime

我一直在尝试将内容脚本中的字符串数组传递给Background环境。我知道在使用JSON.Stringify(); API发送之前,我必须chrome.runtime.sendMessage();任何数据。

我无法成功地做到这一点。有人可以帮助我们缺少什么吗?

先谢谢你。

content_script.js

chrome.extension.sendMessage({}, function(response) { //boilerplate taken from extensionizr.com
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
    clearInterval(readyStateCheckInterval);


    var myArr = ["abc", "def", "ghi"];

    alert("in content_script" + myArr);

    var myJsonString = JSON.stringify(myArr);

    chrome.runtime.sendMessage(myJsonString); //send to background environment


}
}, 10);
});

background.js

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

//var data = JSON.parse(response); // gives token 'o' error (object already a JSON Object)
var data = response;

alert("in background.js, received " + data + " \nfrom tab: " + sender.tab.url);

//console.log(typeof youtube_links); // object ...

document.getElementById("results").innerHTML += "1: " + data[0] + "<br/> 2:" + data[1] + "<br/> 3: " + data[2] + "<br/>";



});

的manifest.json

{
"name": "test",

"version": "0.0.1",

"manifest_version": 2,

"description": "message passing test",

"icons":
{
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
},

"default_locale": "en",

"background": //isolated environment
{
    "scripts": [ "background.js"]
    //"persistent": true
},

"browser_action":
{
    "default_icon": "icons/icon16.png",
    "default_title": "default_title goes here",
    "default_popup": "browser_action.html"
},

"permissions": [
    "clipboardRead",
    "contextMenus",
    "activeTab",
    "tabs"
    ],

"content_scripts": [ //user page environment
    {
        "matches": ["https://*/*", "http://*/*"],
        "js": ["content_script.js"] // will run on URLS that match "matches"
    }
]
}

browser_action.html

<!doctype html>

<html>
<head>

</head>
<style type="text/css">
    #mainPopup {
        padding: 10px;
        height: 200px;
        width: 400px;
        font-family: Helvetica, Ubuntu, Arial, sans-serif;
    }
    h1 {
        font-size: 2em;
    }
</style>
<body>
    <div id="mainPopup">
    <h1>Array Data received from content script:</h1>
    <div id="results">

    </div>
    </div>
</body>
</html>

我得到的是:

这是background.js中的警告

alert("in background.js, received " + data + " \nfrom tab: " + sender.tab.url);

这在browser_action.html

browser_action.html part

P.S。另外,还有一件小事。 content_script.js中的alert();也因某些原因未显示(控制台中也没有错误)

1 个答案:

答案 0 :(得分:2)

首先,您不需要对json对象进行字符串化。 sendMessage()方法可以将任何有效的JSON对象作为要发送的消息。

第二次,我不了解你在第一次调用sendMessage时所做的事情......我认为你必须简单地删除它并让你的代码保持原样:

内容脚本:

var myArr = ["abc", "def", "ghi"];

alert("in content_script" + myArr);

chrome.runtime.sendMessage(myArr);

背景:

chrome.runtime.onMessage.addListener(
    function(response, sender, sendResponse)
    {
        var data = response;

        alert("in background.js, received " + data + " \nfrom tab: " + sender.tab.url);

        document.getElementById("results").innerHTML += "1: " + data[0] + "<br/> 2:" + data[1] + "<br/> 3: " + data[2] + "<br/>";
    }
);

编辑:避免多次通话的痘痘修复:

run = function()
{
    alreadyRun = false;

    return function run()
    {
        if(alreadyRun) return;

        if (document.readyState === "complete")
        {
            var myArr = ["abc", "def", "ghi"];

            alert("in content_script" + myArr);

            chrome.runtime.sendMessage(myArr);
            alreadyRun = true;
        }
        else setInterval(run, 10);
    }
}();

run();

关闭避免声明全局变量的技巧。