首页 > 解决方案 > 在新标签页中打开时重写 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>

标签: javascripthtmljquery

解决方案


一种选择是继续并在页面加载时替换实际的链接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>


推荐阅读