尝试修改HTMLTableRowElement.prototype

Attempt to modify HTMLTableRowElement.prototype

本文关键字:prototype HTMLTableRowElement 修改      更新时间:2023-09-26

我有两个方法,在几个页面中都能很好地工作,但当涉及到Greasemonkey脚本时,它们由于某种原因而失败,抛出了一个"不是函数"错误
同样的代码,虽然正常地附加在页面上,但却能完美地工作。

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

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

由于GM脚本在不同的范围内(名义上)在沙箱中,因此该代码无法从Greasemonkey脚本中工作。有关更多信息和解决方法(@grant none(可能)、脚本注入或unsafeWindow),请参阅"为什么用户脚本中的窗口(和unsafeWindow)与脚本标记中的窗口不同"。

但是,除非您试图更改页面添加的现有代码,否则不要这样做

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


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

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


,并根据需要使用DOM函数添加或删除类。例如:

//--- 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");