riccardo.tasso
riccardo.tasso

Reputation: 1023

Accessing <object> parent from children html

I have two html files:

parent.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Parent</title>
    </head>

    <body>
        <object data="child.html" data-message="hello"></object>
        <object data="child.html" data-message="world"></object>
    </body>

</html>

child.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Child</title>
    </head>

    <body>
        <button onclick="alert('hello world');">press me</button>
    </body>

</html>

I would like that pressing the button rendered by the first object element will alert the data-message of its parent ("hello"). The same for the second button, rendered by the second object with the second message ("world").

Consider that I can only work on the scripts in the child.html file.

Upvotes: 0

Views: 63

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075615

You'll have to have the other company change parent.html some; if you don't, and there are really multiple child.html references in the parent HTML, the child window can't tell which one relates to it. The child windows have access to the parent window, but not to the element (object or iframe) that contains them.

If it's just a message, have the other company pass the message to the child on the query string rather than as a data-message attribute:

<object data="child.html?hello"></object>
<object data="child.html?world"></object>

Then:

alert(location.search.substring(1));

But I assume it's about more than just the message.

So you'll have to have the other company put some kind of marker on the object or iframe that allows you to tell one from the other.

For example:

<object data="child.html?1" data-child="1" data-message="hello"></object>
<object data="child.html?2" data-child="2" data-message="world"></object>

Then in child.html, you can do this when handling the button click:

var childId = location.search.substring(1);
var element = parent.document.querySelector("[data-child='" + childId + "']");
var message = element.getAttribute("data-message");
alert(message);

or as a one-liner:

alert(parent.document.querySelector("[data-child='" + location.search.substring(1) + "']").getAttribute("data-message"));

This works in Chrome, Firefox, and IE11 (provided IE11 isn't in "compatibility" mode).

Upvotes: 2

Related Questions