javascript - 在新标签页中打开时重写 url 不起作用
问题描述
我正在使用 jS 代码将所有出站链接重定向到重定向页面(其中包含让我获利的广告)。它工作得很好。但是当用户选择在新选项卡中打开链接时,它不起作用。有没有办法解决它?
这是我的代码:
<script type='text/javascript'>
jQuery(document).ready(function () {
jQuery('a[href*="http://"]:not([href*="http://example.com"])').click(function (e) {
e.preventDefault();
var target = e.target || e.srcElement;
if ($(target).attr('target') == "_blank") {
window.open("http://example.com/redirect.html?url=" + $(target).attr('href'), '_blank');
} else {
window.location = "http://example.com/redirect.html?url=" + $(target).attr('href');
}
});
});
</script>
解决方案
一种选择是继续并在页面加载时替换实际的链接href,使用如下所示的简单脚本。这样做的另一个好处是,让用户知道他们正在通过不同的站点被重定向更诚实/透明。
const links = document.querySelectorAll('a:not([href*="https://example.com"])');
for (let link of links) {
link.href = `https://example.com/?ref=${link.href}`
}
<a href="https://google.com" target="_blank">Google</a>
<a href="https://yahoo.com" target="_blank">Yahoo</a>
<a href="https://example.com">Internal</a>
推荐阅读
- python - AttributeError: 'Recognizer' 对象没有属性 'listen''
- javascript - Discord.js 消息未定义
- async-await - 如何在 Task.Run 中使用 HttpContext
- java - log4j2新的压缩算法
- python - 在此示例中如何使用 nltk.metrics 中的 edit_distance()?
- c++ - 传递一个向量
> 进入函数给出内存错误 - html - 我的导航栏中有空置空间。我想把搜索栏推到最右边可以做什么
- python - 为什么不使用 starlettes TestClient 使用 pytest-cov 获得 100% 的 FastAPI 覆盖率
- javascript - 无法读取道具,因为对象未定义
- amazon-web-services - 限制对 AWS API Gateway 的 API 调用