问题
I have a page which contains another page embedded inside an object tag. Now I want to call a javascript function from the "parent"-page. To be specific: The parent page wants to call a function, which resides inside the embedded code. Former I used iframes but they caused some nasty bugs with Firefox, so I don't want to use them anymore.
Edit: So, my question is: what would be the best way to achieve this, when using an object tag?
Here's some example to illustrate what I want to do:
I have a HTML page "parent.html" inside this page there is some Javascript inside a tag. This parent.html also has an tag and the src of this tag is another HTML page, let's call it child.html. The child.html page has something like:
Here's some pseudo code:
in Child.html:
<script type="text/javascript" src="child.js"></script>
in Child.js:
function getSomething(){
return something;
}
in Parent.html:
<object id="childObject" data="child.html" width="850" height="510">
</object>
<script>
// Here I want to access the function from the child.js
// I tried something like this, but it doesn't work:
var something = document.getElementById('childObject').contentDocument.getSomething();
</script>
Now: In the Javascript inside the parent.html I need to call a function from the child.js. How can I achieve this?
Thank you :)
回答1:
Using contentWindow
instead of contentDocument
works for me:
<object id="childObject" data="child.html" width="850" height="510">
</object>
<script>
var something = document.getElementById('childObject').contentWindow.getSomething();
</script>
回答2:
You Can try This
<object id="childObject" data="child.html" width="850" height="510">
<script>
var something = document.getElementById("childObject").parentElement.getSomething();
</script>
来源:https://stackoverflow.com/questions/30033163/calling-a-javascript-function-in-html-page-embedded-in-an-object-tag