Extending

2019-04-12 11:25发布

I'm trying to extend the HTMLOptionElement,

<template id="cOptionTemplate">
    <content></content>
</template>

<select>
    <option is="custom-option">Test</option>
</select>
var cOption = document.registerElement('custom-option', {
    prototype: Object.create(HTMLOptionElement.prototype, {
        createdCallback: {
            value: function() {
                var template = document.getElementById("cOptionTemplate")
                var clone = document.importNode(template.content, true);
                this.createShadowRoot().appendChild(clone);
            }
        },
        attributeChangedCallback: {
            value: function (attrName, oldVal, newVal){
                switch(attrName){
                    case "attr1":
                        console.log(this);
                }
            }
        }
    }),
    extends: "option"
});

Here's a demo of the code.

but apparently that doesn't work because it already has a user agent shadowRoot?

Uncaught InvalidStateError: Failed to execute 'createShadowRoot' on 'Element': Shadow root cannot be created on a host which already hosts an user-agent shadow tree.

I have never seen this error and I thought it lets you attach multiple shadow roots. Why is it happening and is there a way to make it work?

1条回答
看我几分像从前
2楼-- · 2019-04-12 11:56

You were right: it was possible to attach multiple shadow roots.

... But this possibility was removed from Chrome to comply with the new version of the Shadow DOM specification (v1), which is now shared with other browser vendors (Mozilla, Microsoft, Apple).

That's why you never saw this error before. It was added to the Living Standard:

  1. If context object is a shadow host, then throw an InvalidStateError.

As a workaround, you have to not use Shadow DOM, or to create a new custom element that doesn't extends the <option> element.

查看更多
登录 后发表回答