window.open和trigger会被浏览器拦截的问题

本文探讨了在特定情况下使用JavaScript触发页面打开时遇到的浏览器拦截问题,并提供了一种有效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天希望做一个效果,即触发某个事件(不一定是点击事件)的同时,打开一个页面。

1. 开始以为很简单:

window.open('http://www.xxxx.com');


2. 后来发现当在window.open被ajax包裹时,被打开的页面会被部分浏览器拦截,如:

$.post(url, data).then(function(data){
window.open('http://www.xxxx.com');
});


3. 想到通过触发某个a标签来实现。
html代码:

<a id="id_link" href="http://www.xxxx.com"></a>

js代码:

$.post(url, data).then(function(data){
$('#id_link').trigger('click');
});


4. 引出了新的问题,a标签没有被点开,几番查找后,修改html和js代码。
html代码:

<a id="id_link" href="http://www.xxxx.com"><span id="id_span"></span></a>

js代码:

$.post(url, data).then(function(data){
$('#id_span').trigger('click');
});


5. 根据以上代码,a标签是被打开了,可是页面还是被浏览器拦截,于是结合2和4。
html代码:

<a id="id_link" href="###"><span id="id_span"></span></a>

js代码:

$('#id_link').click(function(){
window.open('http://www.xxxx.com');
})
$.post(url, data).then(function(data){
$('#id_span').trigger('click');
});


竟然好用了……,浏览器为什么允许这种行为,倒是个新的问题。

话说今天表现的像个菜鸟一样,不过想想,我的确就是个菜鸟,于是风高云淡了。
// ==UserScript== // @name Request Trigger Script // @namespace http://tampermonkey.net/ // @version 2025-03-25 // @description Trigger actions when specific requests are made // @author You // @match https://*/* // @grant none // ==/UserScript== (function () { 'use strict'; // 配置目标域名触发条件 const CONFIG = { TARGET_DOMAINS: [ "nvne.spoken.fun", "nytw.chester.run", "bwxm.chester.run" ], TRIGGER_KEYWORD: "/api/data" // 请求 URL 中包含的关键字 }; // 日志工具 const logger = { info: (...args) => console.log('[Request Trigger]', ...args), error: (...args) => console.error('[Request Trigger]', ...args) }; // 检查是否为目标请求 const isTargetRequest = (url) => { return CONFIG.TARGET_DOMAINS.some(domain => url.includes(domain)) && url.includes(CONFIG.TRIGGER_KEYWORD); }; // 拦截 XMLHttpRequest const interceptXhr = () => { const originalOpen = XMLHttpRequest.prototype.open; const originalSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.open = function (method, url, ...rest) { this._isTarget = isTargetRequest(url); if (this._isTarget) { logger.info('Intercepted XHR request:', method, url); } return originalOpen.apply(this, [method, url, ...rest]); }; XMLHttpRequest.prototype.send = function (body) { if (this._isTarget) { logger.info('Triggering action for XHR request:', this._url); triggerAction(this._url, body); } return originalSend.apply(this, arguments); }; }; // 拦截 fetch 请求 const interceptFetch = () => { const originalFetch = window.fetch; window.fetch = async function (input, init) { const url = typeof input === 'string' ? input : input.url; if (isTargetRequest(url)
03-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值