我试图向我的网页添加一个辅助功能功能,该功能是用React.js构建的,以确保我的横幅的颜色不会受到的影响Chrome高对比度插件。
我尝试通过添加一个函数来检测 Chrome 插件是否已打开来实现它,并且我的代码应该切换一个类以确保横幅颜色在高对比度模式下不会发生太大变化。我注意到这个变化只有在刷新页面后才能看到,所以我添加了这行代码window.location.reload()
来手动重新加载页面。
问题是,这部分代码进入无限循环,我的页面不会停止重新加载。我尝试用其他方法替换重载部分,结果还是一样。这是我的 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%); }
任何帮助都会很好!
最佳答案
为什么不尝试将指标保存到 localstorage
或 sessionstorage
中,并在 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()
}
...
关于javascript - 如何确保函数 "window.location.reload()"只触发一次而不是无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62526093/