替换history.pushState触发事件时遇Illegal invocation错误求助
解决window.history.pushState替换后的Illegal invocation错误
你遇到的TypeError: Illegal invocation错误核心原因是:原生的pushState方法必须在window.history的上下文(即this指向window.history)下调用。你直接调用保存的pushState变量时,this指向的是全局对象(严格模式下为undefined),不符合原生方法的调用要求,因此触发非法调用错误。
修正方案一:调用时用call绑定上下文
const pushState = window.history.pushState; window.history.pushState = function(state, unused, url) { // 触发自定义事件 const event = new Event("someEvent"); window.dispatchEvent(event); // 通过call绑定this到当前history对象,保证原生方法上下文正确 return pushState.call(this, state, unused, url); };
修正方案二:提前用bind绑定上下文
// 提前将原生pushState的this绑定到window.history const pushState = window.history.pushState.bind(window.history); window.history.pushState = function(state, unused, url) { const event = new Event("someEvent"); window.dispatchEvent(event); // 直接调用即可,上下文已经绑定完成 return pushState(state, unused, url); };
额外提示:如果需要监听SPA中所有URL变化(包括replaceState触发的修改),可以用同样的方式替换window.history.replaceState,确保所有历史记录操作都能触发自定义事件。
内容的提问来源于stack exchange,提问作者Rafael Costa
相关产品推荐
相关产品推荐

