基于

2016-10-01 38 views
0

我刚开始使用JavaScript和想修改的MDN教程脚本“匹配” content_scripts运行不同的脚本,Your First WebExtension基于

我想周围画一个红色或蓝色的盒子一个网页取决于它是http://还是https://。但是,只有一个脚本会运行。

的manifest.json的是这样的:

{ 
 

 
    "manifest_version": 2, 
 
    "name": "HTTPS Detect", 
 
    "version": "1.0", 
 

 
    "description": "Draws a blue border around HTTPS protected websites. Non-HTTPS sites are given a red border, indicating they do not provide encryption.", 
 

 
    "icons": { 
 
    "48": "icons/border-48.png" 
 
    }, 
 

 
    "content_scripts": [ 
 
    { 
 
\t 
 
     "matches": ["https://*/*"], 
 
     "js": ["httpsdetect.js"], 
 
     "matches": ["http://*/*"], 
 
     "js": ["nohttps.js"] 
 
     
 
\t } 
 
\t 
 
\t ] 
 
    
 
}

的httpsdetect.js如下:

document.body.style.border = "5px solid blue";

而且nohttps.js被:

document.body.style.border = "5px solid red";

回答

1

content_scripts关键是对象的阵列(每片含强制性matches密钥),而不是仅仅使用相同的按键的多个拷贝的单个对象。您拥有它的方式,您在同一个对象中有两个matches和两个js键。这将在文件的后面解释为覆盖之前的文件中的关键字。

对于每个matches它应该是一个不同的对象在数组中。你的manifest.json可能看起来像:

manifest.json的

{ 

    "manifest_version": 2, 
    "name": "HTTPS Detect", 
    "version": "1.0", 

    "description": "Draws a blue border around HTTPS protected websites. Non-HTTPS sites are given a red border, indicating they do not provide encryption.", 

    "icons": { 
    "48": "icons/border-48.png" 
    }, 

    "content_scripts": [ 
    { 
     "matches": ["https://*/*"], 
     "js": ["httpsdetect.js"] 
    }, 
    { 
     "matches": ["http://*/*"], 
     "js": ["nohttps.js"] 
    } 
    ] 
} 

或者,因为你加载只有一个文件,你可以加载相同的JavaScript文件到两个httphttps页面,并根据URL匹配httphttps更改您正在执行的操作。如果在两个脚本之间共享某些代码的情况下,这样做可能会更有效(或者,您可以将一个文件中的共享代码加载到两个文件中,同时将带有非共享代码的单独文件加载到每个文件中)。在这种情况下,您可以使用与matches阵列中的两个都匹配的单个match pattern或多个匹配模式。