是否可以在两个单独的页面上运行两个内容脚本?

时间:2014-09-03 00:49:25

标签: javascript google-chrome google-chrome-extension content-script

假设我有两个内容脚本,codeA.jscodeB.js。我想知道是否可以在http://www.example.com上运行codeA.js并在http://www.domain.com上运行codeB.js

是否可以将content_scripts文件中的manifest.json设置为:

"content_scripts": [
    {
        "matches": ["http://www.example.com", "http:www.domain.com"],
        "js": ["codeA.js", "codeB.js"]
    }
]

然后让每个脚本检查页面当前所在的URL?如果是这样,我将如何做到这一点?

更新
我尝试使用以下代码

if(document.location == "http://*.google.com/*" || "https://*.google.com/*") {
    alert("you are using google");
} else if(document.location == "http://*.yahoo.com/*" || "https://*.yahoo.com") {
    alert("you are using yahoo!");
}

但我不断获得you are using google

2 个答案:

答案 0 :(得分:3)

请注意,content_scripts数组

"content_scripts": [
    {
        "matches": ["http://www.example.com/*"],
        "js": ["codeA.js"]
    },
    {
        "matches": ["http://www.domain.com/*"],
        "js": ["codeB.js"]
    }
]

答案 1 :(得分:-1)

创建一个脚本文件并检查域名如下所示

if(document.location == domain1){
  // load script file for domain1
} else {
  // load script for other domains
}

AFAIK您无法在manifest.json文件中提及不同域的不同内容脚本文件。

根据您的方法编辑,该代码不起作用。您必须使用正则表达式检查它,而不只是==,因为您的域中包含*。并预先编写Web Accessible Resources脚本。

相关问题