我需要访问一个具有关闭的Shadow DOM的Web组件,以进行一些Selenium测试。我在几个参考文献中读到,可以在文档启动时覆盖
为了测试它,我在一个ASPNetCore MVC项目中创建了我的组件。以下是创建自定义组件的javascript代码:
现在它已经起作用了,Shadow DOM 已经改为打开
Element.prototype.attachShadow
,以将Shadow从关闭状态更改为打开状态。为了做到这一点,我创建了一个Chrome扩展程序。下面是我的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"]
}]
}
还有我的shadowInject.js
console.log('test');
Element.prototype._attachShadow = Element.prototype.attachShadow;
Element.prototype.attachShadow = function () {
console.log('attachShadow');
return this._attachShadow( { mode: "open" } );
};
为了测试它,我在一个ASPNetCore MVC项目中创建了我的组件。以下是创建自定义组件的javascript代码:
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>`;
}
});
并且使用它的我的HTML文件:
@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>
我将我的扩展加载到Chrome中并运行页面。控制台会输出“Test”,但是attachShadow方法从未被调用,因此我仍然无法访问关闭的影子DOM。
我希望你能帮助我找出问题所在。非常感谢。
最终解决方案
在应用了答案中的更改后,我需要对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"]
}],
"web_accessible_resources": ["injected.js"]
}
现在它已经起作用了,Shadow DOM 已经改为打开