簡體   English   中英

如何將子窗口中的事件發送到其父窗口

[英]How can I send an event from child window to its parent window

我的主要目標是:

轉到我的應用程序,在新選項卡中打開一個鏈接,在新選項卡中創建一些內容並將事件發送到父主選項卡進行刷新。

我學到了兩種技術並沒有完全符合我的需要:

  1. postMessage - 據我所知,僅在iframe上而不是在標簽上
  2. window.opener - 僅適用於只打開新窗口而不是新選項卡的window.open(url)。

如何使用制表符將事件從子節點傳遞給父節點? 我很高興在父母和孩子的javascript代碼的具體示例。 它應該適用於跨域(例如:www.mydomain.com和bills.mydomain.com)。

有沒有我錯過的jQuery解決方案?

以下適用於我的chrome,firefox,即(沒有測試更多的瀏覽器)

假設3個文件

  1. www.mydomain.com/parent.html )包含帶鏈接的“main”文檔的頁面
  2. bills.mydomain.com/child.html )將由鏈接打開的頁面
  3. www.mydomain.com/dispatcher.html )稍后解釋

首先將所有3個文檔的域屬性設置為mydomain.com

<script>
document.domain="mydomain.com";
</script>

在parent.html中創建一個隱藏的iframe,其名稱屬性為“hiddenframe”。 還要創建一些稍后可能會收到響應的函數。

parent.html現在應該如下所示:

<script>
document.domain="mydomain.com";
function fx(msg)//receives the response
{
  alert(msg)
}
</script>
<iframe name="hiddenframe" style="display:none"></iframe>
<a href="http://bills.mydomain.com/child.html" target="_blank">click</a>

在child.html中,您現在可以將文檔加載到parent.html中隱藏的iframe中

<script>
document.domain="mydomain.com";
window.open('http://www.mydomain.com/dispatcher.html','hiddenframe');
</script>

(不要混淆面對window.open()這里的使用,不會打開新窗口,頁面將被加載到parent.html中的iframe中)


在dispatcher.html中,您現在可以在parent.html中調用該函數

<script>
document.domain="mydomain.com";
parent.fx('you just got some response');
</script>

當你只需要重新加載parent.html時,它會更容易一些。

再次在parent.html和child.html中設置document.domain-property(在parent.html和dispatcher.html中不需要iframe)

在parent.html中還設置了窗口的name-property,例如

<script>
  window.name="parentTab";
</script>

在child.html中,您現在可以訪問parentTab (選項卡)

<script>
    document.domain="mydomain.com";
    window.open('http://www.mydomain.com/parent.html','parentTab');
</script>

...或者只是使用“parentTarget”作為child.html中鏈接或表單的target-property

我為自己做了什么,我實現了一些ajax從window2向數據庫提交更改。 我實現了JSON將數據從數據庫拉回到window1

通過查看類似的問題只討論window.open (你不想使用)和afaik沒有簡單的方法來獲取所有窗口在同一個域上 ,為了你想要的,你可能需要編寫自己的使用window.sessionStorage執行此操作的框架。
我不認為您可以使用它來訪問子域,但絕對不會訪問其他域。


使用sessionStorage傳遞特定於窗口的消息的實用想法..
你可以通過事物的URL(GET),這樣的方式來傳遞消息可能使父母產生一個唯一的ID為自己parentID ,因為它的唯一ID的孩子childID (這與沿插入URL parentID上點擊如果您使用<a>或隱藏字段,如果您不介意<form method="GET"> ),那么使用sessionStorage使用parentID.childID.timeStamp密鑰將消息保存到父級,父和子中的間隔,從窗口的ID開始查找sessionStorage ,然后是a . ,(即父級查找parentID. )在匹配上將鍵和值復制到新的var,刪除(因此不會再次找到它),然后根據需要進行解析。

我知道這有點羅嗦,但我認為作為一個概念解釋比編寫工作示例代碼要容易得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM