how to pass a value from iframe to the parent?

2019-08-02 15:04发布

问题:

I'm using an iframe to upload an image, so the iframe contains an upload button. It then gets the Image ID, which is needed to save to the database. On the parent page I then have a save button. But I want this save button hidden until the upload button on the iframe is clicked. How I can pass a value from the iframe to the parent? So I need something to let me know the upload button has been clicked. Then pass that value to the parent, and then show the save button. iframe:

<tr>
  <td>
    <asp:LinkButton runat="server" ID="btnUpload" CssClass="btnUpload2" OnClick="btnUpload_Click" Text="Upload"  />
  </td>
</tr>
<tr>
  <td>
    <asp:FileUpload runat="server" ID="fuUpload" />                
  </td>               
</tr>
</table>
</div>
<input type="hidden" id="FileNameHidden" style="display:none" runat="server" clientidmode="Static" />

EDIT

So I added OnClientClick="IsPressed()" to the upload function in the iframe and added this javascript code:

function IsPressed() {
  var pressed = "yes";
  window.parent.uploadPressed(pressed);
}

Then in the parent I added this function:

function uploadPressed(pressed) {
  $("#btnUpdateImage").show();
}

And set the visible to false on the button:

<asp:LinkButton ID="btnUpdateImage" Visible="false" onclick="btnUpdateImage_Click" OnClientClick="CloseImage();return GetDbriefFilename();" CssClass="btnSaveSmall" runat="server" ></asp:LinkButton>

But when I click the uplaod button on the iframe, the save button on the parent isn't displaying. I tested and the value is being passed from the iframe to the parent but why isn't the save button displaying?

回答1:

You have to use cross-document messaging.

For example in the top window:

myIframe.contentWindow.postMessage('hello', '*');

and in the iframe:

window.onmessage = function(e){
    if (e.data == 'hello') {
        alert('It works!');
    }
};