Rob*_*b W 14
要为内容脚本实现可自定义的"匹配模式",需要使用该chrome.tabs.executeScript方法在后台页面中执行内容脚本(在使用chrome.tabs.onUpdated事件侦听器检测到页面加载后).
由于匹配模式检查未在任何API中公开,因此您必须自己创建该方法.它是在实现的url_pattern.cc,并且规范在匹配模式下可用.
这是一个解析器的例子:
/**
* @param String input A match pattern
* @returns null if input is invalid
* @returns String to be passed to the RegExp constructor */
function parse_match_pattern(input) {
if (typeof input !== 'string') return null;
var match_pattern = '(?:^'
, regEscape = function(s) {return s.replace(/[[^$.|?*+(){}\\]/g, '\\$&');}
, result = /^(\*|https?|file|ftp|chrome-extension):\/\//.exec(input);
// Parse scheme
if (!result) return null;
input = input.substr(result[0].length);
match_pattern += result[1] === '*' ? 'https?://' : result[1] + '://';
// Parse host if scheme is not `file`
if (result[1] !== 'file') {
if (!(result = /^(?:\*|(\*\.)?([^\/*]+))(?=\/)/.exec(input))) return null;
input = input.substr(result[0].length);
if (result[0] === '*') { // host is '*'
match_pattern += '[^/]+';
} else {
if (result[1]) { // Subdomain wildcard exists
match_pattern += '(?:[^/]+\\.)?';
}
// Append host (escape special regex characters)
match_pattern += regEscape(result[2]);
}
}
// Add remainder (path)
match_pattern += input.split('*').map(regEscape).join('.*');
match_pattern += '$)';
return match_pattern;
}
Run Code Online (Sandbox Code Playgroud)
在下面的示例中,阵列是硬编码的.实际上,您可以使用localStorage或将匹配模式存储在数组中chrome.storage.
// Example: Parse a list of match patterns:
var patterns = ['*://*/*', '*exampleofinvalid*', 'file://*'];
// Parse list and filter(exclude) invalid match patterns
var parsed = patterns.map(parse_match_pattern)
.filter(function(pattern){return pattern !== null});
// Create pattern for validation:
var pattern = new RegExp(parsed.join('|'));
// Example of filtering:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete') {
var url = tab.url.split('#')[0]; // Exclude URL fragments
if (pattern.test(url)) {
chrome.tabs.executeScript(tabId, {
file: 'contentscript.js'
// or: code: '<JavaScript code here>'
// Other valid options: allFrames, runAt
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
"tabs"- 启用必要的tabsAPI."<all_urls>"- 能够用于chrome.tabs.executeScript在特定页面中执行内容脚本.如果匹配模式集是固定的(即用户无法定义新的匹配模式,只能切换模式),"<all_urls>"则可以用这组权限替换.您甚至可以使用可选权限来减少所请求权限的初始数量(在文档中有chrome.permissions明确说明).
| 归档时间: |
|
| 查看次数: |
743 次 |
| 最近记录: |