我有一个奇怪的问题。 我尝试编写一个在 Firefox 和 Google Chrome 中运行的 GreaseMonkey 脚本。 在 Chrome 中,我尝试了 2 个扩展:“TamperMonkey”和“Blank Canvas Script Handler”,主要是因为我的脚本定期检查外部站点上的新版本,这被视为跨站点脚本编写,并且在 Chrome 中未经授权。
为了向您展示我的问题,我编写了一个简单的测试用例:
// ==UserScript==
// @name test
// @namespace http://fgs.ericc-dream.fr.nf
// @description test gm script
// @include http://gaia.fallengalaxy.eu/
// @author ericc
// @version 0.0.1
// ==/UserScript==
/* We attach an event listener to the body tag and trigger the function
* 'message' each time that an element is inserted in the page */
var el = document.body;
el.addEventListener('DOMNodeInserted', message, false);
var extraFlag = false;
function message(event) {
/* first we capture the id of the new inserted element
* (the one who created the event) */
var objId = event.target.id;
/* add an event listener on the map container */
if (objId == "extra") {
el = document.getElementById('extra');
el.addEventListener('DOMSubtreeModified',readTest,false);
GM_log(el.style.display);
}
}
function readTest() {
el = document.getElementById('extra');
GM_log(extraFlag);
GM_log(el.style.display);
if ((el.style.display != 'none') && (!extraFlag)) {
alert('extra');
extraFlag = true;
} else if ((el.style.display == 'none')) {
extraFlag = false;
}
}
div 元素“extra”被页面修改。问题是 Chrome 无法读取 el.style.display 的值,因此 extraFlag 永远不会再次变为“false”。 我使用这个标志来避免多次运行代码,该网站主要由 JavaScript 驱动 这段代码在 Firefox 中运行得很好!
我尝试使用 Google 进行搜索,但找不到正确答案。看起来很容易改变显示的值,但似乎我是唯一一个尝试读取它的人!!!
我编写此代码是因为 Chrome 不支持“DOMAttrModified”:-(
预先感谢您的帮助
埃里克
最佳答案
我很难准确理解您的问题是什么,但 Chrome 似乎可以很好地读取 .style.display
属性。我只是将以下代码放入 HTML 模板中并将其加载到 Chrome 10 中:
<div id="div1">
</div>
<div id="div2" style="display: block;">
</div>
<div id="div3" style="display: inline;">
</div>
<div id="div4" style="display: none;">
</div>
<script type="text/javascript">
alert(document.getElementById("div1").style.display);
alert(document.getElementById("div2").style.display);
alert(document.getElementById("div3").style.display);
alert(document.getElementById("div4").style.display);
document.getElementById("div1").style.display = "none";
alert(document.getElementById("div1").style.display);
</script>
代码生成了 5 个“警报”框,输出如下:
- block
- 内联
- 无
- 无
看来 Chome 很好地读取了此属性。
也许问题是您运行 Greasemonkey 脚本的网页在 Chrome 中的行为与在 Firefox 中的行为不同?是否该元素的 ID 不同,或者该元素正在从 DOM 中删除而不仅仅是隐藏?如果您通过更多检查来修改函数,会发生什么情况,就像这样?
function readTest() {
el = document.getElementById('extra');
if(el)
{
GM_log(extraFlag);
GM_log(el.style.display);
if (el.style.display && (el.style.display != 'none') && (!extraFlag)) {
alert('extra');
extraFlag = true;
} else if ((el.style.display == 'none') || !el.style.display) {
extraFlag = false;
}
}
else
{
GM_log(extraFlag);
GM_log("element not present");
extraFlag = false;
}
}
这有帮助吗?如果没有,您是否还有其他原因认为 el.style.display 在 Chrome 中无法正确评估?
如果我们更多地了解您尝试使用脚本执行的操作,以及可能尝试在哪些网页或代码上运行该脚本,可能会有所帮助。
关于javascript - Chrome 无法读取 style.display 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5478165/