我正在使用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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句