2 回答

TA贡献1806条经验 获得超8个赞
为什么不尝试将指标保存到localstorageorsessionstorage中,并在 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()
}
...

TA贡献1982条经验 获得超2个赞
您不需要为此重新加载页面,您需要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 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);
添加回答
举报