Override Element.prototype.attachShadow using Chrome Extension

一笑奈何 提交于 2019-12-01 09:20:35

You should not put the code in content_scripts because content_scripts is not the same as the current page context.

You try to change the shadowInject.js code to:

const injectedScript = document.createElement('script');
injectedScript.src = chrome.extension.getURL('injected.js');
(document.head || document.documentElement).appendChild(injectedScript);

Then create a injected.js file in the same directory:

The file content is:

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

You can try it. If there is any problem, please let me know

As mentioned in Black-Hole's answer, content scripts have their own versions of the DOM objects so you'll have to inject an additional script to run in the real DOM.

If you want to touch the page as little as possible and keep shadows closed to the rest of the page you can use this script:

{
  const shadows = new WeakMap();
  const original = Element.prototype.attachShadow;
  Element.prototype.attachShadow = function() {
    const shadow = original.apply(this, arguments);
    shadows.set(this, shadow);
    return shadow;
  };

  // Later...
  shadows.get(document.querySelector("x-element"));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!