Appearance
函数劫持
概念
函数劫持的意思是在一个函数运行之前把它劫持下来,添加我们想要的功能,然后再调用原来的函数执行。这也是常见的钩子函数
的原理之一。
例子
js
var _alert = alert
window.alert = function InjectAlert(...args) {
console.log("alert 之前干啥了")
alert.apply(this, args)
console.log("alert 之后干啥了")
}
应用
- XSS 攻击
通过拦截原生的一些系统函数如 alert eval console
- 钩子函数
反劫持
- 判断函数体是否相同
js
var fakeAlert = function () {}.bind(null)
console.log(window.alert.toString()) // function alert() { [native code] }
console.log(fakeAlert.toString()) // function () { [native code] }
- 创建一个纯净的 iframe 环境,复原原来的函数
js
function createIframe(w) {
var d = w.document
var newIframe = d.createElement("iframe")
newIframe.style.width = 0
newIframe.style.height = 0
d.body.appendChild(newIframe)
newIframe.contentWindow.document.write("<html><body></body></html>")
return newIframe
}
function injectScriptIntoIframe(f, proc) {
var d = f.contentWindow.document
var s = "<script>\n(" + proc.toString() + ")();\n</script>"
d.write(s)
}