Override Element.prototype.attachshadow Using Chrome Extension
I need to access the DOM of a web component that has a closed Shadow DOM for some Selenium testing. I've read in several references that you can override Element.prototype.attachSh
Solution 1:
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');
returnthis._attachShadow( { mode: "open" } );
};
You can try it. If there is any problem, please let me know
Solution 2:
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 = newWeakMap();
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"));
}
Post a Comment for "Override Element.prototype.attachshadow Using Chrome Extension"