Pas*_*cal 3 javascript google-chrome-extension shadow-dom
我需要访问具有关闭的Shadow DOM的Web组件的DOM,以进行某些Selenium测试。我读过一些参考资料,您可以Element.prototype.attachShadow在文档启动时重写这些参考资料,以将“阴影”从“关闭”更改为“打开”。为此,我创建了一个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"]
}]
}
Run Code Online (Sandbox Code Playgroud)
还有我的shadowInject.js
console.log('test');
Element.prototype._attachShadow = Element.prototype.attachShadow;
Element.prototype.attachShadow = function () {
console.log('attachShadow');
return this._attachShadow( { mode: "open" } );
};
Run Code Online (Sandbox Code Playgroud)
为了对其进行测试,我在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>`;
}
});
Run Code Online (Sandbox Code Playgroud)
和使用它的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://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
<x-element id='comp'></x-element>
</div>
Run Code Online (Sandbox Code Playgroud)
我将扩展程序加载到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"]
}
Run Code Online (Sandbox Code Playgroud)
您不应将代码放在content_scripts中,因为content_scripts与当前页面上下文不同。
您尝试将shadowInject.js代码更改为:
const injectedScript = document.createElement('script');
injectedScript.src = chrome.extension.getURL('injected.js');
(document.head || document.documentElement).appendChild(injectedScript);
Run Code Online (Sandbox Code Playgroud)
然后injected.js在同一目录中创建一个文件:
文件内容为:
console.log('test');
Element.prototype._attachShadow = Element.prototype.attachShadow;
Element.prototype.attachShadow = function () {
console.log('attachShadow');
return this._attachShadow( { mode: "open" } );
};
Run Code Online (Sandbox Code Playgroud)
你可以试试。如果有任何问题,请告诉我