Greasemonkey不允许扩充Element.prototype,说"不是函数"

时间:2017-07-10 04:21:08

标签: javascript firefox prototype greasemonkey tampermonkey

我需要在我的用户脚本中定义Element.prototype内的方法,但是当我尝试这样做时,我会遇到奇怪的错误:

// ==UserScript==
// <...>
// @grant        none
// ==/UserScript==

;[Element.prototype, Text.prototype].forEach(e => {
  e.findParent = function(selector) {
    let node = this
    while(node && !node.matches(selector)) {
      node = node.parentNode
      if (! node.matches) return null;
    }
    return node
  }
}
  

[...]。forEach(...)不是函数

function augmentPrototype(e) {
  e.findParent = function(selector) {
    /* <...> */
  }
}
augmentPrototype(Element.prototype)
  

augmentPrototype不是函数

(e => {
  e.findParent = function(selector) {
    /* <...> */
  }

})(Element.prototype)
  

(中间值)(...)不是函数

似乎在Element.prototype上调用了任何函数,它立即成为&#34;而不是函数&#34;到Greasemonkey,甚至是[].forEach

在普通的Firefox控制台中没有这样的问题。我也修改了Event.prototype,它运行正常。

更新:对于Firefox的Tampermonkey也存在同样的问题,因此它不仅仅是Greasemonkey的问题。

1 个答案:

答案 0 :(得分:-1)

抱歉,误报。事实证明,在我的代码旁边,我有一个以(...开头的立即调用函数,我不使用分号。在IIF解决问题之前领先的分号。显然,自动分号插入在Firefox中的工作方式略有不同,因为它在Chrome中运行良好。