猿问

如何确保函数“window.location.reload()”只触发一次而不是无限循环?

我试图向我的网页添加一个可访问性功能,它是用 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%); }


你能帮忙的话,我会很高兴!


白板的微信
浏览 225回答 2
2回答

慕森卡

为什么不尝试将指标保存到localstorageorsessionstorage中,并在 if 条件中添加此验证:您的代码片段:...// Use local or session storagelet 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()}...

临摹微笑

您不需要为此重新加载页面,您需要MutationObserver.这将在特定元素上查找文档中的更改。当hc属性被动态添加到页面时,它将在添加或删除它时进行侦听。"High Contrast", "a4"如果打开高对比度模式(“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 observedconst 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 functionconst observer = new MutationObserver(callback);// Start observing the target node for configured mutationsobserver.observe(targetNode, config);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答