Short answer: Use Object.create()
for the prototype object. The following code allows you to extend the script
element, and represents the way document.registerElement()
is meant to be used.
var scriptData = document.registerElement('script-data', {
prototype: Object.create(HTMLScriptElement.prototype);
});
Long answer
Consider this variation on your original code:
var scriptDataProto = HTMLScriptElement.prototype;
// The next statement throws a DOMException of type "NotSupportedError".
var scriptData = document.registerElement('script-data', {
prototype: scriptDataProto
});
The source of the exception is illustrated here:
scriptDataProto === HTMLScriptElement.prototype; // true
You're providing a reference to HTMLScriptElement.prototype
, meaning that you want to use the exact same prototype for the custom script element you're creating. It's not very well documented yet, but the prototype you provide can't be a reference to any of the built-in HTML[*]Element
prototypes; you have to provide a new prototype object.
If you want to inherit from the <script>
tag's prototype, then you have to create a new prototype object that inherits from HTMLScriptElement.prototype
by using Object.create()
.
var scriptDataProto = Object.create(HTMLScriptElement.prototype);
scriptDataProto === HTMLScriptElement.prototype; // false
If you'd like, you can then add new members to this prototype without affecting the base HTMLScriptElement.prototype
.
scriptDataProto.foo = function() {
alert('Hello world!');
};
var scriptData = document.registerElement('script-data', {
prototype: scriptDataProto
});
var element = new scriptData();
element.foo(); // alerts "Hello world!"
document.body.appendChild(element);
element.onclick = element.foo;
For further reading, HTML5 Rocks has a well-written article that really helped me understand how custom elements work.