Asynchronous communication cross pages

杀马特。学长 韩版系。学妹 提交于 2020-01-24 22:15:19

问题


I have a page addin.html. It can popup another page editor (which is not necessarily in the same domain) by

popup = window.open("https://localhost:3000/#/posts/editor/", "popup")

Then, the two pages have each one listener inside, and can send data to each other by

// listen:
function receiveMessage(event) {
    document.getElementById("display").innerHTML = JSON.stringify(event.data);
}
window.addEventListener("message", receiveMessage, false);

// send:
function sendMessage() {
    popup.postMessage("data", popup.location.href);
}

editor is realised by ui-router. Initially, it resolves init before loading the page:

.state('editor', {
    controller: 'EditorCtrl',
    resolve: { init: [ ... ] },
    ...
};

app.controller('EditorCtrl', ['$scope', 'init', function ($scope, init) {
    ...
}]

What I want to implement now is, when addin.html popups editor, it sends some data to editor, and init needs to resolve this data, before loading the page. editor could hang before receiving the data from addin.html.

Does anyone know how to amend the receivers and senders (and something else) to accomplish this?


回答1:


You could return a custom promise and resolve it whenever you want as the following code

.state('editor', {
  controller: 'EditorCtrl',
  resolve:{
    init: function($q){
         var deferred = $q.defer();
         window.addEventListener("message", function(event){
              deferred.resolve(event.data);
         }, false);
         return deferred.promise;
     }
  }
});

The controller waits for above item to be completely resolved before instantiation.



来源:https://stackoverflow.com/questions/42702333/asynchronous-communication-cross-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!