我有一个奇怪的问题。我尝试编写一个在 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 元素“额外”由页面修改。问题是 Chrome 无法读取 el.style.display 的值,因此 extraFlag 永远不会再次变为“假”。我使用这个标志来避免多次运行代码,该网站大量使用 JavaScript 驱动此代码在 Firefox 中运行良好!
我试图用谷歌搜索,但找不到正确的答案。更改显示值似乎很容易,但似乎只有我一个尝试阅读它!
我编写此代码是因为 Chrome 不支持“DOMAttrModified”:-(
在此先感谢您的帮助
埃里克