'不安全-EVAL'在chrome扩展

时间:2014-10-07 18:24:03

标签: javascript google-chrome-extension

我正在尝试运行以下内容:

chrome.tabs.onCreated.addListener(function (tab){
    if (tab.url.indexOf(".salesforce.com/") != -1 || tab.url.indexOf(".force.com/") != -1) {
        chrome.tabs.executeScript(tab.id, {
            "file": "loadScript.js"
        }, function () {
            console.log("Script Executed .. ");
        });
    } else {
        var wrongTab = chrome.i18n.getMessage("wrongTab");
        console.log(wrongTab);
        alert(wrongTab);
    }
});

哪个(理论上),在页面加载时运行loadScript.js文件.... loadScript.js文件如下,这应该将文件附加到正在运行的页面,而不是后台页面,因为它是目前:

/* Create a scriipt element in head of HTML and put /soap/ajax/31.0/connection.js in the src  */
var connectJsUrl = "/connection.js";

function loadScript(url, callback) {
    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement("script");
    script.src = url;
    var done = false;
    script.onload = script.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
            done = true;
            callback();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        }
    };
    head.appendChild(script);
}

loadScript(connectJsUrl, function() {
    console.log("Script Confirmed...")
});

/* Check to see if the file have been appended correctly and works correctly */
var JSFile = "chrome-extension://" + window.location.host + connectJsUrl;
var req = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
if (req == null) {
    console.log("Error: XMLHttpRequest failed to initiate.");
};
req.onload = function() {
    try {
        eval(req.responseText);
    } catch (e) {
        console.log("There was an error in the script file.");
    }
};
try {
    req.open("GET", JSFile, true);
    req.send(null);
} catch (e) {
    console.log("Error retrieving data httpReq. Some browsers only accept cross-domain request with HTTP.");
};

我仍然是Chrome Extensions和.js的新手,请原谅我,如果我犯了一个愚蠢的错误:)

我从中获得的是以下内容: 拒绝将字符串评估为JavaScript,因为' unsafe-eval'在以下内容安全策略指令中不是允许的脚本源:" script-src' self'铬扩展资源:"

2 个答案:

答案 0 :(得分:9)

为防止跨网站脚本,Google已阻止了评估功能。

要解决此问题,请将此代码添加到 manifest.json

"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",

如果您需要进一步说明,请发表评论

答案 1 :(得分:0)

重要事项

如前所述,将其添加到您的 manifest.json 中:

"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"

确保将“manifest_version”设置为 2 又名

//this
"manifest_version": 2

由于某些安全原因,在 manifest_version 3 上运行的 Chrome 扩展不支持不安全的评估。

还要确保重新加载您的扩展。