webaction via promise

raw

load.htm

1
<script type="text/javascript" src="js/webaction-promise.js"></script>
raw

webaction-promise.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Lazy-create and return an indie-config load promise
// The promise will be resolved with a config once the indie-config has been loaded
var loadIndieConfig = function () {
 
    // Create the Promise to return
    var loadPromise = new Promise(function (resolve) {
 
        // Parse the incoming messages
        var parseIndieConfig = function (message) {
 
            // Check if the message comes from the indieConfigFrame we added (or from some other frame)
            if (message.source !== indieConfigFrame.contentWindow) {
                return;
            }
 
            var indieConfig;
 
            // Try to parse the config, it can be malformed
            try {
                indieConfig = JSON.parse(message.data);
            } catch (e) {}
 
            // We're done – remove the frame and event listener
            window.removeEventListener('message', parseIndieConfig);
            indieConfigFrame.parentNode.removeChild(indieConfigFrame);
            indieConfigFrame = undefined;
 
            // And resolve the promise with the loaded indie-config
            resolve(indieConfig);
        };
 
        // Listen for messages from the added iframe and parse those messages
        window.addEventListener('message', parseIndieConfig);
 
        // Create a hidden iframe pointing to something using the web+action: protocol
        var indieConfigFrame = document.createElement('iframe');
        indieConfigFrame.src = 'web+action:load';
        document.getElementsByTagName('body')[0].appendChild(indieConfigFrame);
        indieConfigFrame.style.display = 'none';
    });
 
    // Ensure that subsequent invocations return the same promise
    loadIndieConfig = function () {
        return loadPromise;
    };
 
    return loadPromise;
};
 
loadIndieConfig().then(
    function() {
        console.log("yuri");
    }
).catch(
    function() {
        console.log("fail");
    }
);
Christian Weiske Christian Weiske
owner

History