0

我无法从后台脚本获取内容脚本请求值。

content_script.js
=================
var elements = undefined
var properties = undefined
var targets = undefined
chrome.extension.sendRequest({greeting: "elements"}, function(response) {
    elements = response.input;
});
if (elements == undefined){
    var elements = ["a","img"];
}else{
    elements = elements.split(',');
}
chrome.extension.sendRequest({greeting: "properties"}, function(response) {
    properties = response.input;
});
if (properties == undefined){
    var properties = ["alt","id","class"];
}else{
    properties = properties.split(',');
}
chrome.extension.sendRequest({greeting: "targets"}, function(response) {
    targets = response.input;
});
if (targets == undefined){
    var targets = ["onclick","href"];
}else{
    targets = targets.split(',');
}...
...More code and references to elements following...

上面的代码仅在代码中断(即等待)之前才有效,然后再执行与上面设置的值相关的任何操作,我想我可以做一些事情来做到这一点,但如果可能的话,我更愿意使用更有效的解决方案。

(以供参考:)

background.js
=============
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
    switch (request.greeting){
        case "elements":
                var elements = localStorage["elements"];
                sendResponse({input: elements});
                break;
        case "properties":
                var properties = localStorage["properties"];
                sendResponse({input: properties});
                break;
        case "targets":
                var targets = localStorage["targets"];
                sendResponse({input: targets});
                break;
        }
  });

我已经在这里呆了 3 个小时(仍在学习我在用 JS 做什么)

4

1 回答 1

0

嗯,你不能这样做:

chrome.extension.sendRequest({greeting: "properties"}, function(response) {
    properties = response.input;
});
if (properties == undefined){ // always undefined
    var properties = ["alt","id","class"];
}else{
    properties = properties.split(',');
}

sendRequest是异步的。

检查未定义的正确方法是:

if (typeof properties == "undefined") 

如果您需要所有这些东西,只需发出 1 个请求并在回调中执行所有操作:

chrome.extension.sendRequest({greeting: "all"}, function(response) {
    if (response.elements === null) {
        var elements = ["a","img"];
    } else {
        var elements = response.elements.split(',');
    }

    if (response.properties === null) {
        var properties = ["alt","id","class"];
    } else {
        var properties = response.properties.split(',');
    }

    if (response.targets === null) {
        var targets = ["onclick","href"];
    } else {
        var targets = response.targets.split(',');
    }
});

在后台:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    switch (request.greeting){
        case "all":
            sendResponse({
                elements: localStorage.getItem("targets"),
                properties: localStorage.getItem("properties"),
                targets: localStorage.getItem("targets")
            });
            break;
    }
});
于 2012-04-18T15:38:27.697 回答