问题
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