使用chrome扩展重写用户定义的函数以使用本机函数



我对JS和创建chrome扩展相当陌生,我使用了Array.filter函数,但对于一些网站,网站所有者创建了自己的Array.filter功能,其行为与内置函数不同。有没有任何方法可以覆盖这个用户定义的函数并获得这个函数的本机行为。如有任何帮助,我们将不胜感激。

要保存原始的Array#过滤器方法,只需将其保存到一个变量中,然后在需要时使用call():

//Saving the original method
var ArrayFilter = Array.prototype.filter;
//Then whenever needing to use it, call it by using call()
var someArray = [1,2,3];
var filteredArray = ArrayFilter.call(someArray,function(){ /* your filter callback */ });

现在,您需要在创建修改后的filter()方法的脚本之前运行此操作。要做到这一点,您必须更改内容脚本的加载点,以便它可以加载其他代码。这是通过在清单中设置run_at设置来完成的:

清单:

"content_scripts": [
{
"matches": ["http://*.example.com/*"],
"run_at": "document_start",
"js": ["contentScript.js"]
}
],

contentScript.js

//injecting the script into the page
//or however you are currently doing it
var yourScript = document.createElement('script');
document.head.appendChild(yourScript);
yourScript.textContent = "/* your js code */";

在页面脚本之前运行代码,并使用Object.defineProperty重新定义方法并禁止后续更改。您需要将该代码放在DOMscript元素中,以便它在页面上下文中运行(更多信息(,使用文本字符串而不是src属性,以确保它位于任何其他页面脚本之前(更多信息。

manifest.json:

"content_scripts": [{
"matches": ["https://foo.bar/*"],
"js": ["content.js"],
"run_at": "document_start",
"all_frames": true
}]

content.js:

const script = document.createElement("script");
script.textContent = `
Object.defineProperty(Array.prototype, 'filter', {
value: Array.prototype.filter,
configurable: false,
writable: false,
});
`;
document.documentElement.appendChild(script);
script.remove();

相关内容

最新更新