Aaronius / penpal

A promise-based library for securely communicating with iframes via postMessage.
MIT License
389 stars 56 forks source link

add support for file protocol #26

Closed ylesaout closed 5 years ago

ylesaout commented 5 years ago

The file protocol is a special case when using the postMessage API. Below you will find a test case showing it doesn't work currently. Just open the parent.html file in your browser from your file system. It display "Connection Status : success" if the connection is working and "Connection Status : failed" if not.

This PR adds the file protocol support. I added comments in the code to point to HTML specification and or MDN documentation when appropriate. It works with absolute and relative file: URLs.

Let me know if I need to update the implementation.

parent.html

<!DOCTYPE html>
<html>
<head>
    <script src="https://unpkg.com/penpal/dist/penpal.min.js"></script>
    <script type="text/javascript">
        function insertConnectionStatusToDOM(status) {
            var div = document.createElement('div');
            div.textContent = "Connection Status : " + status;
            document.body.appendChild(div);
        }
        function createChilds() {
            var connection = Penpal.connectToChild({
                url: './child.html',
                //url: 'file://<REPLACE_WITH_ABSOLUTE_PATH_TO_YOUR_CHILD_HTML_FILE>',
                timeout: 2000
            });
            connection.promise
            .then(function() {
                insertConnectionStatusToDOM("success");
            })
            .catch(function(){
                insertConnectionStatusToDOM("failed");
            });

        }
        window.addEventListener("load", createChilds);
    </script>
</head>
<body></body>
</html>

child.html

<!DOCTYPE html>
<html>
<head>
    <script src="https://unpkg.com/penpal/dist/penpal.min.js"></script>
    <script type="text/javascript">
        Penpal.connectToParent();
    </script>
</head>
<body></body>
</html>
Aaronius commented 5 years ago

This is great. Thanks for the contribution!

Aaronius commented 5 years ago

Published in v3.1.0.