X秒後にユーザーを新しいページにリダイレクトするスクリプトがあります。リダイレクトされた後、ユーザーが戻るボタンを押してこのスクリプトのページに戻った場合、スクリプトが再度起動されないようにしたいと思います。
setTimeout(function() {
window.location.href = "/mypage.html";
}, 3000);
X秒後にユーザーを新しいページにリダイレクトするスクリプトがあります。リダイレクトされた後、ユーザーが戻るボタンを押してこのスクリプトのページに戻った場合、スクリプトが再度起動されないようにしたいと思います。
setTimeout(function() {
window.location.href = "/mypage.html";
}, 3000);
次のようにJavaScriptでreferrerプロパティを取得できます。
var referrer_url = document.referrer;
document.write("You come from this url: " +referrer_url);
次に、条件付きチェックでラップしてsetTimeout()
、その人がどのURLから来ているかを確認し、どこから来たかに応じてリダイレクトを実行します(または実行しません)。
私はCerbrusが提供したリンクを使用し、これを解決するためにCookieルートを使用しました。私が望んでいたよりも複雑でしたが、それで仕事は終わりました。
このスクリプトは、3秒後にユーザーを新しいページにリダイレクトします。最初にCookieが存在するかどうかを確認し、存在する場合はリダイレクトしません。Cookieがない場合は、Cookieが作成され、ユーザーがリダイレクトされます。ユーザーが戻るボタンを押すと、スクリプトは作成されたCookieを検出し、スクリプトがユーザーを再度リダイレクトするのを防ぎます。
// Function to create a new cookie
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
// Function to read a cookie
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
// Use the readCookie function to assign the cookie to a variable (if it's available)
var currentcookie = readCookie('mycookie');
// If/else statement to fire javascript if the cookie is not present
if (currentcookie) {
// do nothing since the cookie exists
}
else {
// Cookie doesn't exist, so lets do our redirect and create the cookie to prevent future redirects
// Create a cookie
createCookie('mycookie','true');
// Perform the redirect after 3 seconds
setTimeout(function() {
window.location.href = "/mypage.html";
}, 3000);
}