[英]Javascript communicating cross-domain to parent window of iframe
我編寫了一個用於做筆記,從網頁上抓取圖像的工具。 通過使用javascript書簽,它可以將自己作為iFrame加載到當前窗口中:
javascript:(function(){ _my_script=document.createElement('SCRIPT'); _my_script.type='text/javascript'; _my_script.src='http://basereality.test/js/bookmarklet.js?rand='+(Math.random()); document.getElementsByTagName('head')[0].appendChild(_my_script); })();
我希望能夠通過在用戶單擊關閉按鈕時從父窗口中刪除iFrame來關閉該工具。
最簡單的方法是-是否可以在自己內部關閉iFrame?
我嘗試使用跨域消息發布。 我有跨域發布工作,從父窗口到子iFrame,但從iFrame到父窗口不起作用。
到目前為止,我擁有的代碼(可能包含問題)如下。
在父窗口中通過動態加載的Javascript:
function addiFrame(domain){
var iframe_url = "http://" + domain + "/bookmarklet";
var div = document.createElement("div");
div.id = bookmarkletID;
var str = "";
iframe_url += "?description=" + encodeURIComponent(document.title);
iframe_url += "&URL=" + encodeURIComponent(document.URL);
str += "<div>";
str += "<iframe frameborder='0' class='toolPanelPopup dragTarget' style='z-index: 1000' name='bookmarklet_iframe' id='bookmarklet_iframe' src='" + iframe_url + "' width='550px' height='255px' style='textalign:right; backgroundColor: white;' />";
str += "</div>";
div.innerHTML = str;
document.body.insertBefore(div, document.body.firstChild);
}
function jQueryLoadedCallback(){
jQueryAlias = jQuery.noConflict();
jQueryAlias('#' + bookmarkletID).bind('basereality.removeFrame', removeFrame);
}
function removeFrame(){
alert("Calling remove frame");
$("#" + bookmarkletID).remove();
}
在iFrame中,用於關閉iFrame調用的按鈕:
function removeFrame(){
var params = {};
params.message = 'basereality.removeFrame';
parent.postMessage(params, "*");
}
iFrame中的removeFrame調用不會導致在父窗口中調用removeFrame。
因此,我實際上應該如何刪除iFrame。
postMessage可能就是您想要的。 Mozilla已對此進行了記錄,並具有相當不錯的跨瀏覽器支持:
https://developer.mozilla.org/zh-CN/docs/DOM/window.postMessage
我也圍繞這個概念編寫了一個庫,它可能需要一些調試,但是可以在github上找到: https : //github.com/tsharp/OF.Core.js/blob/master/js/of/window.messaging。 js
從這里開始,您將需要父窗口上的事件偵聽器來處理所有傳入請求...這將從父上下文中刪除iframe。 這是注冊消息接收事件的示例。
function registerWindowHandler() {
if (typeof window.addEventListener !== 'undefined') {
window.addEventListener('message', receiveMessage, false);
} else {
// Support for ie8
window.attachEvent('onmessage', receiveMessage);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.