首页 > 解决方案 > JavaScript 事件函数在每个页面加载时运行一个

问题描述

body我在页面的 HTML 部分中放置了一个事件 javascript 函数。

<script type="text/javascript">

    function CookiebotCallback_OnAccept() {
        window.location.reload(true);
        if (Cookiebot.consent.statistics)
        {

        }
    }
</script>

此脚本会导致无限刷新,因为每次加载页面时都会运行该函数。我该怎么做才能使此功能仅在调用时才运行,而不是在每个页面加载时自动运行?

标签: javascript

解决方案


localStorage我的解决方案是在or中创建一个标志变量sessionStorage,然后检查是否已经有该变量,跳过调用重新加载。

<script type="text/javascript">   
    function CookiebotCallback_OnAccept() {
      if(!sessionStorage.getItem('isReloaded')) {
        sessionStorage.setItem('isReloaded', true);

        window.location.reload(true);

        if (Cookiebot.consent.statistics)
        {

        }
      }
    }
</script>
// you can also clear the variable to trigger the reload again.
// By: sessionStorage.removeItem('isReloaded');
// Note: the sessionStorage will be cleared each time you close the browser, 
// while localStorage is only by uninstalled the browser or manually.

推荐阅读