尝试修改HTMLTableRowElement.prototype

时间:2014-04-21 02:48:59

标签: javascript greasemonkey

我有两种方法,可以在几页中很好地工作,但是当涉及到Greasemonkey脚本时,由于某种原因它们会失败,抛出'不是函数'错误。
正常附加到页面的代码完全相同。

HTMLTableRowElement.prototype.hideRow = function(){this.style.display = 'none'};
HTMLTableRowElement.prototype.showRow = function(){this.style.display = ''};

在调用其中一个函数时出现错误。有线索吗?

1 个答案:

答案 0 :(得分:1)

由于GM脚本位于不同的范围内且(名义上)位于沙箱中,因此该代码无法使用Greasemonkey脚本。有关详细信息和解决方法(@grant none(可能),或脚本注入或unsafeWindow),请参阅"Why is window (and unsafeWindow) not the same from a userscript as from a script tag"

但是,除非您尝试更改由/添加到页面的现有代码,否则不会这样做。

使用jQuery的.hide().show().toggle()


或者使用GM_addStyle()创建一个类,EG:

GM_addStyle (".GM_hide {display: none !important;}");


使用DOM函数根据需要添加或删除类。 EG:

//--- Select the 2nd row of the first table
var someRow = document.querySelector ("table tr:nth-of-type(2)");

someRow.classList.add    ("GM_hide");
someRow.classList.remove ("GM_hide");
someRow.classList.toggle ("GM_hide");