我使用 Polymer-cli(0.16.0 版)搭建了一个聚合物项目,但无法使用控制台访问 shadow-root:
var element = document.getElementsByTagName("my-app")[0].shadowRoot
返回 undefined 所以看起来影子 DOM 处于关闭模式。
如何强制自定义元素使用打开模式,以便我可以从外部访问它的 shadowRoot?
编辑 2:这里的主要问题是访问 shadowRoot 需要做什么,所以我稍微改变了问题,使其与 shadow DOM 模式无关
编辑:
参考https://developers.google.com/web/fundamentals/getting-started/primers/shadowdom#advanced高级主题部分的关闭模式
重现场景的步骤:
npm install -g polymer-cli
mkdir my-app
cd my-app
polymer init starter-kit
polymer serve --open
一些代码片段:
索引.html:
...
<head>
...
<script>
// Setup Polymer options
window.Polymer = {
dom: 'shadow',
lazyRegister: true
};
// Load webcomponentsjs polyfill if browser does not support native Web Components
(function() {
'use strict';
var onload = function() {
// For native Imports, manually fire WebComponentsReady so user code
// can use the same code path for native and polyfill'd imports.
if (!window.HTMLImports) {
document.dispatchEvent(
new CustomEvent('WebComponentsReady', {bubbles: true})
);
}
};
var webComponentsSupported = (
'registerElement' in document
&& 'import' in document.createElement('link')
&& 'content' in document.createElement('template')
);
if (!webComponentsSupported) {
var script = document.createElement('script');
script.async = true;
script.src = '/bower_components/webcomponentsjs/webcomponents-lite.min.js';
script.onload = onload;
document.head.appendChild(script);
} else {
onload();
}
})();
// Load pre-caching Service Worker
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/service-worker.js');
});
}
</script>
<link rel="import" href="/src/my-app.html">
...
</head>
<body>
<my-app></my-app>
</body>
</html>
我的应用程序.html:
...
<dom-module id="my-app">
<template>
...
</template>
<script>
Polymer({
is: 'my-app',
properties: {
page: {
type: String,
reflectToAttribute: true,
observer: '_pageChanged'
}
},
observers: [
'_routePageChanged(routeData.page)'
],
_routePageChanged: function(page) {
this.page = page || 'view1';
},
_pageChanged: function(page) {
// Load page import on demand. Show 404 page if fails
var resolvedPageUrl = this.resolveUrl('my-' + page + '.html');
this.importHref(resolvedPageUrl, null, this._showPage404, true);
},
_showPage404: function() {
this.page = 'view404';
}
});
</script>
</dom-module>