我需要确保某些特定的原生 Javascript 函数没有被修补或覆盖。
不幸的是,我无法通过访问 .toString()
来做到这一点。函数或 Function.prototype.toString
使用绑定(bind)应用或调用之一,因为 Function.prototype.toString
是我必须测试的功能之一。
是否有任何其他方法可以返回函数的值(函数本身)? (或 [Native Code]
用于原生 JS 函数)
编辑:此测试的目的之一是检查客户端是否是修补某些 JS 功能的机器人。创建新框架并获取其Function.prototype.toString
在这种情况下,值(value)将不起作用
最佳答案
回应编辑
如果它是一个无法或不会更新其机器人脚本以响应您的检查的恶意客户端,则只需保存 Function.prototype.toString()
的副本在 HTML header 中使用 javascript 到临时变量。然后检查这个以查看客户端是否完全改变了 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
如果可以限制使用最新的火狐,可以使用
.toSource()
的方法, 但没有其他浏览器支持它并且它不是标准的。 More reading here// only in latest Firefox
const x = () => 'wow';
console.log(x.toSource())
// returns "() => 'wow'"
作为一个框架挑战,您可能仍在使用
Function.prototype.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;
关于javascript - 如何在没有 toString() 的情况下获取函数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60423627/