重定向后运行函数一次

Run function once after redirecting

本文关键字:一次 运行 函数 重定向      更新时间:2023-09-26

我正在尝试将访问网站的用户重定向到移动网站。到目前为止,我已经做了这些,但问题是每次加载页面时,函数都会一直运行。这些函数在页面加载后被调用。我是JavaScript初学者。

function redirectPage() {
    var runOnce = 0;
    if (runOnce == 0 && windowWidth <= 767){
        runOnce = 1;
        window.location.assign("example.net/mobile-site");
    }
    else if (runOnce == 0 && windowWidth >= 767){
        runOnce = 1;
        window.location.assign("example.net/regular-site");
    }
}

更新

这就是我所做的,但到目前为止,浏览器一直在加载。

var windowWidth = 0;
$(document).ready(function(){
    checkBrowserWidth();
    redirectPage(); 
});
function checkBrowserWidth() {      
    windowWidth = window.outerWidth;
}
function redirectPage() {
    if (typeof(Storage) != 'undefined') {
        // Store value 
        localStorage.setItem('runOnce', 0);
    }
    var runOnce = localStorage.getItem('runOnce');
    if (runOnce == 0 && windowWidth <= 767){
        localStorage.setItem('runOnce', 1);
        window.location.assign("example.net/mobile-site");
    }
    else if (runOnce == 0 && windowWidth >= 767){
        localStorage.setItem('runOnce', 1);
        window.location.assign("example.net/regular-site");
    }
}

您的方法存在几个问题。

范围

JavaScript具有函数范围。这意味着runOnce将始终是redirectPage函数之外的undefined。因此,每个呼叫都会将runOnce作为undefined

console.log(window.setSomething); // undefined
function scopeExample() {
  var setSomething = 'something';
}
console.log(window.setSomething); // undefined

如果要保存全局变量,则需要将其设置在全局作用域(如window)上。

// this will be set on a global-basis, however it will not affect the next request as 
// explained in the next section
window.runOnce = 0;
function redirectPage() {    
    if (window.runOnce == 0 && windowWidth <= 767){
        window.runOnce = 1;
        window.location.assign("example.net/mobile-site");
    }
    else if (runOnce == 0 && windowWidth >= 767){
        window.runOnce = 1;
        window.location.assign("example.net/regular-site");
    }
}

脚本生存期

想象一下,每个页面加载都是一个单独的应用程序。除非你愿意,否则它不知道以前的请求。你需要将其保存在cookie或客户端存储(如localStorage)中。

function redirectPage() {
    var runOnce = localStorage.get('runOnce');
    if (runOnce == '0' && windowWidth <= 767){
        localStorage.set('runOnce', '1');
        window.location.assign("example.net/mobile-site");
    }
    else if (runOnce == '0' && windowWidth >= 767){
        localStorage.get('runOnce', '1');
        window.location.assign("example.net/regular-site");
    }
}