前端新开一个选项卡后不断重定向,如何知道最初的重定向?
jerkzhang
用下面一段代码,来阻止跳转,输出到要跳转的页面在调试栏里:
// 拦截 window.open 方法 const originalOpen = window.open; window.open = function(url, target, features) { console.log('[ 拦截] 新开窗口请求:', url); return null; // 阻止实际打开行为 }; // 拦截 <a target="_blank"> 点击事件 document.addEventListener('click', function(e) { const link = e.target.closest('a[target="_blank"]'); if (link) { e.preventDefault(); console.log('[ 拦截] 新标签页跳转:', link.href); } }, true); // 使用捕获阶段确保拦截 // 拦截通过 window.open 的异步调用(如 AJAX 回调) const eventHandler = function(e) { if (typeof e.target.onclick === 'function') { const originalOnclick = e.target.onclick; e.target.onclick = function(event) { const result = originalOnclick.call(this, event); if (typeof result === 'object' && result instanceof Window) { console.log('[ 拦截] 异步窗口请求:', result.location.href); result.close(); } return result; }; } }; document.addEventListener('mouseup', eventHandler, true); document.addEventListener('touchend', eventHandler, true);