一直以来,我们都在使用这个可靠的网站重定向 HTML/JavaScript 代码
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="1;url=https://www.nosuchwebsite.com">
<script type="text/javascript">
window.location.href = "https://www.nosuchwebsite.com"
</script>
<title>Page Redirection</title>
</head>
<body>
<!-- Note: don't tell people to `click` the link, just tell them that it is a link. -->
If you are not redirected automatically, follow the <a href='https://www.nosuchwebsite.com'>nosuchwebsite</a>
</body>
</html>
现在,我们希望在重定向之前执行 Google Analytics 跟踪代码。
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxxxxx-x']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
我意识到,元“刷新”可能会早于 JavaScript 跟踪代码执行。我想知道是否有任何方法可以使 Google Analytics 跟踪代码在元“刷新”之前运行
长脚本的解决方案
如果脚本需要相当长的时间并且我们不确定需要多长时间,我们不想指定秒数。
所以我们的想法是从元数据中获取要重定向的 URL,然后重定向到它,
- 停止刷新,
window.stop();
-
你会编写脚本吗
-
最后从meta获取URL并重定向到它。
window.location = document.querySelector( '[http-equiv="refresh"]' ).content.split( 'url=' )[1];
这是一个例子
// STEP 1: Stop currect redirection
window.stop();
// STEP 2: Do your script stuff
// promise? async/await? Do wtf you want.
const msgEl = document.getElementById( 'messages' );
const addMsg = msg => msgEl.innerHTML += msg + '<br>';
setTimeout( () => addMsg( 'Let me at least do my nails.' ), 1000 );
setTimeout( () => addMsg( 'Aah, I\'m having a bad hair day :(' ), 2000 );
setTimeout( () => addMsg( 'Almost done...' ), 3000 );
setTimeout( () => addMsg( 'Ok, just a (three) second(s)...' ), 4000 );
setTimeout( () => {
addMsg( 'Redirecting...' );
// STEP 3: Redirect, Finally done with every we wanted to do.
window.location = document.querySelector( '[http-equiv="refresh"]' ).content.split( 'url=' )[1];
}, 7000 );
/* Arbitrary CSS for presentation purposes only */
p, h3, small {
font-family: sans-serif;
font-weight: 300;
line-height: 2
}
p {
font-size: 14px;
}
code {
font-family: monospace;
}
<!-- Resides somewhere inside <head> tag. -->
<meta http-equiv="refresh" content="0;url=https:///google.com/">
<!-- Arbitrary html for illustration -->
<h3>
Please wait while you are redirected with the mighty <code>meta refresh</code>.
</h3>
<p id='messages'></p>
<small><b>Spoiler:</b> Redirection will be stopped even though <code>meta[http-equiv="refresh"]</code> refreshes in 0 seconds.</small>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)