有没有人有一个如何以角度发送和接收window.postMessage()调用的工作示例?我在github和ngmodules上找到了ng-post-message模块,但是我看一下这段代码并没有对我有多大意义,而且文档缺乏一个有效的例子。
视图
<div simulation-host element="thing in things"></div>
</div>
<div id="debugConsole">
<h1>MESSAGE CONSOLE</h1>
<p id="debugText"></p>
</div>
模型
$scope.things =
[
{
"location" : "Foobar",
"resource" : $sce.trustAsResourceUrl("http://external.domain:14168/Foo/Bar"),
"title" : "Launch"
}
];
我尝试指示
var simulationFrameHost = angular.module('proxy.directives', []);
simulationFrameHost.config(function ($sceDelegateProvider){
//URL Regex provided by Microsoft Patterns & Practices.
$sceDelegateProvider.resourceUrlWhitelist(['^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$','self']);
});
simulationFrameHost.directive('simulationHost', ['$window',function($window) {
return {
retrict: 'ACE',
transclude: 'element',
replace: true,
scope: true,
template: [
'<ul>',
'<li>',
'<span>',
'<a href="#">',
'{{thing.location}}',
'</a>',
'</span>',
'<messenger>',
'<iframe ng-src="{{thing.resource}}" />',
'</messenger>',
'</li>',
'</ul>'
].join(''),
compile: function (tElement, tAttrs, transclude) {
var interval;
var show = function(msg)
{
var debugText = document.getElementById("debugText");
if(debugText){
debugText.innerHTML += msg + "<br/>";
}
};
var rpt = document.createAttribute('ng-repeat');
rpt.value = tAttrs.element;
console.log(tAttrs.element);
tElement[0].children[0].attributes.setNamedItem(rpt);
$(tElement[0].children[0].children[0].children[0]).on("click", function(event){
console.log(event);
var iframe = tElement[0].children[0].children[1].children[0].contentWindow;
show("Initiating connection with: " + event.currentTarget.host);
var message = {
action: 'syn',
param: 'connection'
};
interval = setInterval(function(){
//*****************************************
iframe.postMessage(JSON.stringify(message), 'http://'+ event.currentTarget.host);
//*****************************************
}, 500);
return false;
});
}
}
}]);
请注意,此代码使用弹出窗口而不是iframe;遇到了IE浏览器之间的postMessage被破坏的复杂性,所以必须回到iframe。
标记
<body>
<div id="debugConsole">
<h1>MESSAGE CONSOLE</h1>
<p id="debugText"></p>
</div>
<h1>This is a test</h1>
<ul>
<li>
<a href= "http://external.domain:14168/Foo/Bar" target="_blank" ><p>Foobar</p></a>
</li>
</ul>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-animate/angular-animate.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="js/SCORM_API_wrapper.js"></script>
<script src="js/json2.js"></script>
<script src="js/plugins.js"></script>
<script src="js/index.js"></script>
</body>
index.js
$('a').on("click",function(event){
console.log(event);
var pop = window.open(event.currentTarget.href, 'poop');
show("Initiating connection with: " + event.currentTarget.host);
var message = {
action: 'syn',
param: 'connection',
};
interval = setInterval(function(){
pop.postMessage(JSON.stringify(message), 'http://'+ event.currentTarget.host);
}, 500);
return false;
});
$(window).on("message", function(e) {
clearInterval(interval);
var eventData = JSON.parse(e.originalEvent.data);
show("Message received from: " + e.originalEvent.origin);
if(eventData.action) {
switch (eventData.action) {
case 'syn-ack':
ack(e.originalEvent, eventData.param, eventData.value);
break;
case "set":
show("Set request received: " + e.originalEvent.data);
set(eventData.param, eventData.value);
break;
case "get":
show("Get request received: " + e.originalEvent.data);
var value = get(eventData.param);
var response = {
action: "response",
type: "get",
param: eventData.param,
value: value
};
e.originalEvent.source.postMessage(JSON.stringify(response), channel);
break;
}
}
});
在我的指令编译中,我试图将click事件连接到生成的锚标记。我试图让点击向iframe发布消息,但是iframe.postMessage什么也没做。它刚刚进入幽冥,我从今天上午10点起就开始研究这个问题了。我的眼睛开始上釉了:p
1)iframe to parent
2)window to window
(&lt; =是的,我已经知道这在IE中不起作用)
我有遗留代码工作,通过生成窗口来执行窗口消息传递窗口 第二篇文章&#34; syn&#34;创建后立即向它发送消息。然后第二个窗口收到消息为&#34; syn&#34;并将发件人存储为messageHandle,以便它可以维护一个频道来发布返回消息,然后返回一个&#34; syn-ack。&#34;发起人跟进了一个&#34; ack&#34;辅助窗口收到确认并继续工作。 (如果ack在超时之前没有返回,我记录了连接失败,然后在一段时间内轮询辅助窗口以尝试恢复连接)
答案 0 :(得分:4)
我无法使用Angular指令。我拉了一个浪费的所有黑客试图完成“正确的方式”,并希望我早点抛出这个想法,因为我的要求并不是真的值得。这个东西不必扩展,因为它是用于在X-Domain系统之间提供消息传递代理的目的构建软件。
'use strict'
var app = angular.module('domain.system.controllers', ['services.proxy.mine']);
app.controller('ProxyCtrl', ['$scope', '$routeParams', '$window', '$sce', 'MyService',
function ( $scope, $routeParams, $window, $sce, MyService)
{
$($window).on("message", function(e){
var message = JSON.parse(e.originalEvent.data);
if(message.recipient){
switch(message.recipient){
case: "ProxyCtrl":
//handle message;
break;
}
}
}
}
]);
答案 1 :(得分:3)
刚刚发过这篇文章,这可能会对你有所帮助。
(function() {
'use strict';
angular
.module('postmessage')
.factory('iFrameMessagingService', iFrameMessagingService);
iFrameMessagingService.$inject = ['$window', '$location', '$rootScope', '$log'];
function iFrameMessagingService($window, $location, $rootScope, $log) {
var service = {
sendMessage : sendMessage
};
activate();
return service;
function activate(){
activateIncomingMessageHandler();
}
function activateIncomingMessageHandler(){
$window.addEventListener('message', function(event){
if (typeof(event.data) !== 'undefined'){
// handle message
}
});
}
function sendMessage(message){
// Dispatch the event.
$log.debug(message);
if($window.parent !== $window){
$window.parent.postMessage(message, '*');
}
}
}
})();