未捕获的ReferenceError&意外的令牌错误

时间:2013-11-03 11:19:17

标签: javascript json google-chrome-extension

我正在将amazon link localizer转换为Chrome扩展程序。 我目前正在处理的错误是:

  

未捕获的ReferenceError:未定义checkAmazonLinks

发布此JSON的网址是:https://freegeoip.net/json/?callback=checkAmazonLinks 我在我的JS文件中调用它:

function findLocation() {
if (typeof google != "undefined" && google.loader.ClientLocation != null) {
    var strCountry = google.loader.ClientLocation.address.country_code;
    checkAmazonLinks(strCountry)
    console.log(strCountry)
} else {
    objScript = document.createElement("script");
    objScript.src = "https://freegeoip.net/json/?callback=checkAmazonLinks";
    document.getElementsByTagName("head")[0].appendChild(objScript);
}

这是我的manifest.js:

{
"name"              : "amazon linker",
"version"           : "0.1",
"manifest_version"  : 2,
"description"       : "A simple extension that turns all Amazon links on a page into localized affiliate links",
"permissions"     : [ "http://*/*","https://*/*"],
"browser_action": {
    "default_title": "Amazon Linker"
},
"content_security_policy": "script-src 'self' https://google.com; https://freegeoip.net;  object-src 'self'",

"content_scripts": [{
        "matches": ["<all_urls>"],
        "js": ["amazon-localiser.js"]
    }
],
 "web_accessible_resources": ["amazon-localiser.js","amazon-localiser.php"]
}

我尝试在freegeoip中从json请求中删除回调,但后来我收到错误

  

Uncaught SyntaxError:意外的令牌:

我的.js中有一个函数调用checkAmazonLinks(),在findLocation()之后加载,我尝试重新排列顺序,但这没有帮助。我们的想法是在checkAmazonLinks()通过具有相同函数名称的回调检索JSON之前在.js中定义findLocation()。我如何通过此错误?

1 个答案:

答案 0 :(得分:0)

内容脚本在 isolated world (沙盒环境)中运行。您已在内容脚本的上下文中定义了 checkAmazonLinks 函数,但https://freegeoip.net/json/?callback=checkAmazonLinks是在Web页面的JS上下文中注入并执行的(因为内容脚本和网页共享DOM)。
问题是在网页的上下文中,没有定义checkAmazonLinks函数。

<强>解决方案:

:一种。)
在向checkAmazonLinks发出请求之前,也会将https://freegeoip.net/...函数注入网页。 E.g:

...
} else {
    objScript1 = document.createElement("script");
    objScript1.innerHTML = "function checkAmazonLinks(...) {...}";
    document.getElementsByTagName("head")[0].appendChild(objScript1);

    objScript = document.createElement("script");
    objScript.src = "https://freegeoip.net/json/?callback=checkAmazonLinks";
    document.getElementsByTagName("head")[0].appendChild(objScript);
}

<强> B中。)
在内容脚本的上下文中创建(和处理)请求。例如。对https://freegeoip.net/json进行AJAX调用并将响应传递给checkAmazonLinks函数。