Search code examples
javascriptweb-componentshadow-domcustom-element

Why can I call function which is in a shadow dom?


I created a custom element called "memory-box" like the below code.
Please pay attention to the function "logthis" which is in "memory-box-template".

memory-box.html

<template id="memory-box-template">
    <input id="memory-box" type="form" />
    <input type="button" id="testbutton" />
    <script type="text/javascript">
    function logthis(me){
        console.log(me);
    }    
    </script>
</template>

<script type="text/javascript">
    (function() {
        var thisDoc = document.currentScript.ownerDocument;
        var storage = localStorage;

        var proto = Object.create(HTMLElement.prototype, {
            createdCallback: {
                value: function() {                
                    var temp = thisDoc.querySelector('#memory-box-template');
                    var con = document.importNode(temp.content, true);
                    this.createShadowRoot().appendChild(con);
                    var input = this.querySelector('::shadow #memory-box');
                    var data = storage.getItem(this.id);
                    input.value = data;
                    input.addEventListener('input', saveData.bind(input, this.id));
                }
            },
        });

        document.registerElement('memory-box', {
            prototype: proto
        });

        function saveData(id, e) {
            storage.setItem(id, this.value);
        }
    })();
</script>

Now, I uses the custom element "memory-box" like the below code.

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <link rel="import" href="/html/memory-box.html">
</head>

<body>
    <div><memory-box id="memory1"></memory-box></div>
    <div><memory-box id="memory2"></memory-box></div>
    <div><memory-box id="memory3"></memory-box></div>
    <div><memory-box id="memory4"></memory-box></div>   
</body>

<script type="text/javascript">
    logthis(this);
</script>

</html>

As you can see, I putted a script in the index.html and called the function "logthis" just because I was curious. And no error occurred.
Why?
The function "logthis" is in each shadow doms. It's supposed not able to be called outside the shadow dom, I think.


Solution

  • As explained here, while the HTML within Shadow DOM is encapsulated, any JavaScript is NOT -- it is in the global scope, unless you utilize specific javascript techniques (namescaping, IIFE) to do so.

    Hope this helps,

    Jonathan Dodd