我需要确保某些特定的本机Javascript函数没有被修补或覆盖。
[不幸的是,我无法通过绑定应用或调用之一访问功能的.toString()
或Function.prototype.toString
,因为Function.prototype.toString
是我必须测试的功能之一。
还有其他方法可以返回函数的值(函数本身)吗? (或[Native Code]
用于本机JS函数)
您可以重新请求整个.js文件,并将其全部解析为字符串。您将必须对每个js文件执行此操作,并找到一个好的模式来确定函数是否已被覆盖,因此它可能无法满足您的需求。
// my JS file is being served from giorgiosjames.com/myjs.js
const myJs = await fetch('giorgiosjames.com/myjs.js').then(res => res.text());
// parse myJs here, something like
if (myJs.includes('Function.prototype.toString = ')) // do something
如果可以限制使用最新的Firefox,则可以使用.toSource()
方法,但是没有其他浏览器支持它,这不是标准方法。 More reading here
// only in latest Firefox
const x = () => 'wow';
console.log(x.toSource())
// returns "() => 'wow'"
作为一个框架挑战,您可能仍然可以通过以下方式使用(可能是)Function.prototype.toString
的最佳方法:
首先检查toString是否有效。
如果已覆盖.toString()
,则将其重置。
.toString()
检查其他功能.toString()
let temp = null;
if (Function.prototype.toString.toString() !== 'function toString() { [native code] }') {
// save overridden function if you need to come back to it
temp = Function.prototype.toString;
// getting the original toString function by creating an iframe
const iframe = docuemnt.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
Function.prototype.toString = iframe.contentWindow.Function.prototype.toString;
}
// do your other checks here ex//
if (Array.prototype.includes.toString() !== iframe.contentWindow.Array.prototype.includes.toString()) {
// do something
}
// ..or however you're planning on checking for overridden functions
// restore toString from temp if needed.
Function.prototype.toString = temp;