When creating an HTML custom element with a JSON string embedded by the user (though the type of string is not relevant here) ...
<my-elem>
{ "some":"content" }
</my-elem>
I would like to JSON.parse
it like this ...
class MyElement extends HTMLElement {
constructor() {
super();
this.root = this.attachShadow({ mode:'open' });
this.root.appendChild(template.content.cloneNode(true));
}
connectedCallback() {
JSON.parse(this.innerHTML);
}
}
customElements.define('my-elem', MyElement);
const template = document.createElement('template');
template.innerHTML = `irrelevant`;
... and get a perfect result with Firefox v.63.
But running this with Chrome v.71 I get
Uncaught SyntaxError: Unexpected end of JSON input
due to this.innerHTML
returning an empty string.
I also tried other DOM methods to access the textual content, but all of them failed also.
Now I'm rather clueless, how to get this to work with Chrome.
Btw: Using <slot>
is of no help, since I do not want to render the textual content ... only access it for parsing.
Resolved:
- Put the template definition before the class definition.
- Ensure having the script defining the custom element inserted behind all custom element instances in the HTML document.