您好我已经为我们公司的机器编写了以下扩展程序,实际上应该从我们的网络服务器上保存的列表中删除任何数字。
虽然这有效,但它显着减慢了媒体/网页的加载速度,并且chrome似乎可以查看数字列表(例如,当这种情况发生时,例如刷新图标)。
任何有助于更好地实现相同结果的帮助或指导都将受到极大的赞赏。
[highlight.js]
// This array will all of the numbers to highlight
var numberArray = [''];
var UPDATE_INTERVAL = 57600; // Update after 1 Minute
// Retrieve script from storage
chrome.storage.local.get({
lastUpdated: 0,
code: ''
}, function(items) {
if (Date.now() - items.lastUpdated > UPDATE_INTERVAL) {
// Get updated file, and if found, save it.
get('http://webaddress/highlight.js', function(code) {
if (!code) return;
chrome.storage.local.set({lastUpdated: Date.now(), code: code});
});
}
if (items.code) // Cached script is available, use it
execute(items.code);
else // No cached version yet. Load from extension
get(chrome.extension.getURL('highlight.js'), execute);
});
//
function execute(code) {
try { window.eval(code); } catch (e) { console.error(e); }
// Run number replacement.
numberArray.forEach(function(v){
var number = v;
ve = new RegExp(number, "g");
document.body.innerHTML = document.body.innerHTML.replace(ve,"DO-NOT-CALL");
});
}
function get(url, callback) {
var x = new XMLHttpRequest();
x.onload = x.onerror = function() { callback(x.responseText); };
x.open('GET', url);
x.send();
}
[的manifest.json]
{
"background": {
},
"content_scripts": [ {
"js": [ "highlight.js"],
"run_at" : "document_idle",
"matches": [ "http://*/*", "https://*/*" ],
"css": [ "style.css" ]
} ],
"content_security_policy": "script-src 'self' 'unsafe-eval' https://ssl.google-analytics.com; object-src 'self'",
"description": "Detect telephone numbers and remove blocked numbers.",
"icons": {
"128": "icon_128.png",
"16": "icon_16.png",
"32": "icon_32.png",
"48": "icon_48.png"
},
"manifest_version": 2,
"name": "CLS Call Bar",
"permissions": [ "tabs", "storage", "http://*/*", "https://*/*" ],
"version": "1.0.0"
}
答案 0 :(得分:0)
您正在为每个看起来非常低效的数字替换整个文档的innerHTML
document.body.innerHTML = document.body.innerHTML.replace(ve,"DO-NOT-CALL");
相反,您可以在其直接父ID /类中使用数字作为标识符,如此
<span id="number-holder-{{number}}">{{number}}</span>
(它可能已经像这样,因为它是一种常见的模板练习)
并在您的内容脚本中执行类似
的操作numberArray.forEach(function(v){
document.getElementById("number-holder-"+v).innerHTML = "DO-NOT-CALL"
}
如果不能选择更改HTML,那么使用document.body.innerHTML作为初始值对临时变量进行正则表达式替换,并在循环后将其赋值回来。
答案 1 :(得分:0)
我已经成功地解决了这个问题,感谢Aman Verma指出我更换了整个innerHTML我已经改变了以下内容并且它现在非常有效......
这
numberArray.forEach(function(v){
var number = v;
ve = new RegExp(number, "g");
document.body.innerHTML = document.body.innerHTML.replace(ve,"DO-NOT-CALL");
});
到
numberArray.forEach(function(v){
var treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT),
textNode;
while(textNode = treeWalker.nextNode()) {
if(textNode.parentElement.tagName !== 'SCRIPT') {
textNode.nodeValue = textNode.nodeValue.replace(v, "DO NOT CALL THIS NUMBER");
}
}
});