- 需要权限
"permissions": [
"contextMenus"
],
- 在
background
创建菜单
this.createMenus();
/**
* 创建菜单
*/
createMenus() {
// 1.添加hostname到白名单
chrome.contextMenus.create({
"title" : `添加当前域名到白名单`,
"type" : "normal", // 菜单项类型 "checkbox", "radio","separator"
"contexts" : ["page","frame"], // 菜单项影响的页面元素 "anchor","image"
"documentUrlPatterns":["*://*/*"], // iframe的src匹配
"targetUrlPatterns" : ["*://*/*"], // href的匹配
"onclick" : this.addWhiteList // 单击时的处理函数
});
}
/**
* 添加白名单
*/
addWhiteList() {
chrome.tabs.getSelected(null, (tab) => {
try{
let uri = new URL(tab.url);
let pat = /([a-zA-Z0-9.-]*\.[a-zA-Z]{1,4})|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
if (pat.test(uri.hostname)) {
let whitelist = localStorage.getItem('Config.whitelist') || '';
let white_array = whitelist===''?[]: whitelist.split("\n");
if (!white_array.includes(uri.hostname)) {
white_array.unshift(uri.hostname)
}
localStorage.setItem('Config.whitelist', white_array.join("\n"));
}
} catch(e) {
console.log('ignore')
}
});
}
网友评论