window.location 导致连续循环使用

window.location causing continuous loop using

我正在尝试将基于特定条件的查询字符串附加到 URL。我遇到的问题是,以下代码导致页面不断循环:

function taoExtendedIdleTime() {
  if (trackingJson.loginType === 'explicit') {
    var myURL = window.location;
    window.location = myURL + "&debugMode=true&setIdleTime=60000";
  } 
} 

taoExtendedIdleTime();

为了更正此问题,我尝试了以下操作,检查此查询是否已存在。如果没有,请添加:

function taoExtendedIdleTime() {
  if (trackingJson.loginType === 'explicit') {
    var myURL = window.location;
      if (myURL.indexOf("&debugMode=true&setIdleTime=60000") == -1) {
        window.location = myURL + "&debugMode=true&setIdleTime=60000";
      }
  } 
} 

taoExtendedIdleTime();

在我的开发环境中,这根本不会执行。当我将它添加到控制台时,出现以下错误:Uncaught TypeError: myURL.indexOf is not a function, and references the fourth line of this snippet: if(myURL.indexOf...).

您可以提供任何 help/guidance,我们将不胜感激!!

基于documentationwindow.location是一个Location对象(不是String),所以它没有indexOf方法.不过您可能对其 search 属性 感兴趣。

或者,如果您想变得更干净,URL.searchParams 可能会有所帮助。

因为您正在尝试获取一个对象。 window.location 将 return 你的 Location 对象。您正在寻找的是 window.location.href,它将 return url 当前位置。

function taoExtendedIdleTime() {
   if (trackingJson.loginType === 'explicit') {
       var myURL = window.location.href;       
       window.location.href = myURL + "&debugMode=true&setIdleTime=60000";
} }
taoExtendedIdleTime();