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.attachShadow
on the document startup in order to change the Shadow from closed to open. In order to do this, I created a Chrome Extension. Below is my manifest.json
:
{
"name": "SeleniumTesting",
"description": "Extension to open closed Shadow DOM for selenium testing",
"version": "1",
"author": "SeleniumTesting",
"manifest_version": 2,
"permissions": ["downloads", "<all_urls>"],
"content_scripts": [{
"matches": ["http://localhost:5000/*"],
"run_at": "document_start",
"all_frames": true,
"js": ["shadowInject.js"]
}]
}
And my shadowInject.js
console.log('test');
Element.prototype._attachShadow = Element.prototype.attachShadow;
Element.prototype.attachShadow = function () {
console.log('attachShadow');
return this._attachShadow( { mode: "open" } );
};
In order to test it, I created my component in an ASPNetCore MVC project. Below is my javascript that creates the custom component:
customElements.define('x-element', class extends HTMLElement {
constructor() {
super();
this._shadowRoot = this.attachShadow({
mode: 'closed'
});
this._shadowRoot.innerHTML = `<div class="wrapper">
<a href="download/File.pdf" download>
<button id="download">Download File</button>
</a>
<p>Link para download</p>
</div>`;
}
});
And my HTML file that uses it:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<script src='~/js/componente.js'></script>
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
<x-element id='comp'></x-element>
</div>
I load my extension into Chrome, and I run the page. I get the console log Test, but the attachShadow method is never called, and I still cannot access the closed shadow DOM
I would really appreciate some help on what I`m doing wrong. Thank you very much.
FINAL SOLUTION
After applying the changes in the answer, I need to make some adjustments to the manifest.json
. Below is the final version:
{
"name": "SeleniumTesting",
"description": "Extension to open closed Shadow DOM for selenium testing",
"version": "1",
"author": "SeleniumTesting",
"manifest_version": 2,
"permissions": ["downloads", "<all_urls>"],
"content_scripts": [{
"matches": ["http://localhost:5000/*"],
"run_at": "document_start",
"all_frames": true,
"js": ["shadowInject.js"]
}],
"web_accessible_resources": ["injected.js"]
}