如何替换Element原型方法?

时间:2018-06-19 07:34:05

标签: firefox greasemonkey-4

我应该怎么做才能让它在greasemonkey中运作?:

Element.prototype._attachShadow = Element.prototype.attachShadow;
Element.prototype.attachShadow = function () {
    return this._attachShadow( { mode: "open" } );
};

现在,当我使用它时: document.body.attachShadow({mode:"closed"}).innerHTML = "dec";

这是错误:

  

错误:拒绝访问对象的权限

如何让应用程序使用替换方法?

编辑(更多信息):

Firefox Nightly 62.0a1(2018-06-18)(64 bity)

Greasemonkey 4.4.0

// ==UserScript==
// @name     Unnamed Script 124585
// @version  1
// @grant    none
// @include http://kind-clarke-ced7cb.bitballoon.com/
// ==/UserScript==


Element.prototype._attachShadow = Element.prototype.attachShadow;
Element.prototype.attachShadow = function () {
    return this._attachShadow( { mode: "open" } );
};
console.log("US work");

经测试的页面: http://kind-clarke-ced7cb.bitballoon.com/

<div id="test" style="border: 1px solid silver;">xxx</div>

<div id="info">wait 4 sec...(so that UserScript can load itself before)</div>
   <script>
setTimeout(()=>{
  document.querySelector("#test").attachShadow({mode:"closed"}).innerHTML = "dec";
  document.querySelector("#info").innerHTML += `<br/>run: document.querySelector("#test").attachShadow({mode:"closed"}).innerHTML = "dec";`;
}, 3000);

setTimeout(()=>{
  document.querySelector("#info").innerHTML += `<br/>shadowRoot of #test is: ${(document.querySelector("#test").shadowRoot)}`;
}, 4000);
    </script>

现在替换attachShadow方法根本不起作用。

#test的shadowRoot返回null但应该是[object ShadowRoot],因为UserScript会强制它。

1 个答案:

答案 0 :(得分:0)

shadowdom在FF版本59中默认为禁用。要启用它,需要修改首选项。

转到about:config->搜索dom.webcomponents.shadowdom.enabled->双击以切换布尔值(将其设置为true)->重新加载页面。

MDN Docs for reference

现在替换将可用。经过Firefox Quantum 60.0.2 (64 bit)Firefox Nightly 62.0a1 (64 bit)

的测试

但是通过Inspect Element检查时,在HTML树中看不到shadow元素。 BugZilla

中还报告了一个错误。

在控制台中仅记录一条信息消息Shadow DOM used in [site-link] or in some of its subdocuments.。 (消息仅在每晚版本中显示)

编辑: 经过一番挖掘,发现使用unsafeWindow可以解决您的问题。 Little detail about unsafeWindow

// ==UserScript==
// @name     Unnamed Script 124585
// @version  1
// @grant    none
// @include  http://kind-clarke-ced7cb.bitballoon.com/
// ==/UserScript==

unsafeWindow.Element.prototype._attachShadow = unsafeWindow.Element.prototype.attachShadow;
unsafeWindow.Element.prototype.attachShadow = function () {
    return this._attachShadow( { mode: "open" } );
};
console.log("US work");
setTimeout(()=>{
  document.querySelector("#test").attachShadow({mode:"open"}).innerHTML = "dec";
  document.querySelector("#info").innerHTML += `<br/>run: document.querySelector("#test").attachShadow({mode:"closed"}).innerHTML = "dec";`;
}, 1000);

setTimeout(()=>{
    document.querySelector("#info").innerHTML += `<br/>shadowRoot of #test is: ${(document.querySelector("#test").shadowRoot)}`;
}, 2000);

由于modeclosed,因此替换无效。将其更改为open

相关问题