【问题标题】:How to make sure the function "window.location.reload()" only fires once instead of having an infinite loop?如何确保函数“window.location.reload()”只触发一次而不是无限循环?
【发布时间】:2020-10-13 00:04:42
【问题描述】:

我试图在我的网页中添加一个 可访问性 功能,该功能是用 React.js 构建的,以确保我的横幅颜色不会受到 的影响Chrome 的高对比度插件。

我尝试通过添加一个函数来检测 Chrome 插件是否已打开来实现它,并且我的代码应该切换一个类以确保横幅颜色在高对比度模式下不会发生太大变化。我注意到这个变化只有在刷新页面后才能看到,所以我添加了这行代码window.location.reload()来手动重新加载页面。

问题是,这部分代码进入了一个无限循环,我的页面不会停止重新加载。我尝试用其他方法替换reloading部分,结果还是一样。这是我的 React 组件的代码:

 componentDidMount = () => {
    this.keepBannerColor()
}


keepBannerColor() {
    // these two lines of code below is tell whether the browser is chrome
    let userAgentString = navigator.userAgent;
    let chromeAgent = userAgentString.indexOf("Chrome") > -1;
    let header = document.querySelector('.mizaru-header')

    if (header && chromeAgent) {
        console.log('funciton triggered')
        let htmlTag = document.getElementsByTagName('html');
        let isInverted = htmlTag[0].getAttribute('hc') != null
        header.classList.toggle('inverted', isInverted)
        window.location.reload()
    }
}

这是我的切换类 CSS 代码:.inverted{ filter: invert(100%); }

任何帮助都会很好!

【问题讨论】:

  • 您不需要重新加载页面来更改 css 类。
  • 此外,如果您从服务器重新加载文档,您对文档所做的任何更改都将丢失。

标签: javascript reactjs google-chrome dom accessibility


【解决方案1】:

您不需要为此重新加载页面,您需要MutationObserver

这将查找文档中特定元素的更改。

由于hc 属性是动态添加到页面中的,因此它会在添加或删除时进行监听。

如果开启了高对比度模式(“a4”会根据设置发生变化),下面将记录"High Contrast", "a4",如果插件未激活,则会记录“高对比度关闭”。

下面的美妙之处在于,根据设置“a3”、“a4”等,您可以应用不同的样式。

当插件被禁用时,下面的内容有些不正确,好像两次触发“高对比度关闭”,因此您需要对此进行调查。 (这是因为当插件关闭时,它首先将状态设置为“a0”,然后删除属性,在正常使用情况下应该没问题,但只是需要注意的一点)。

  const targetNode = document.documentElement;

// Options for the observer (which mutations to observe)
const config = { attributes: true};

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    // Use traditional 'for loops' for IE 11
    
    let name = "";
    
    for(let mutation of mutationsList) {
       if (mutation.type === 'attributes') {
           if(mutation.attributeName == "hc"){
               if(mutation.target.attributes.getNamedItem(mutation.attributeName) != null && mutation.target.attributes.getNamedItem(mutation.attributeName).value != "a0"){
               console.log("High Contrast", mutation.target.attributes.getNamedItem(mutation.attributeName).value);
           }else{
               console.log("High Contrast Off");
           }
           }
            
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

【讨论】:

    【解决方案2】:

    您为什么不尝试将指标保存到localstoragesessionstorage,然后在您的 if 条件中添加此验证:

    您的代码片段:

    ...
    // Use local or session storage
    let hasReloaded = localStorage.getItem('hasReloaded')
    
    if (header && chromeAgent && !hasReloaded) {
      console.log('funciton triggered')
      let htmlTag = document.getElementsByTagName('html');
      let isInverted = htmlTag[0].getAttribute('hc') != null
      header.classList.toggle('inverted', isInverted)
      // Set hasRealoaded to true
      localStorage.setItem('hasReloaded', true)
      window.location.reload()
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多