Hello StackOverflow community,
I was having a problem with my <iframe>
and JavaScript. Let's say I have an index.html with an iframe
in the body. Within the index.html
I have this in the <head>
tags:
<script type="text/javascript">
function alertTest() {
alert("Testing");
}
</script>
In the iframe's src="iframe.htm"
(The location is the same domain as index.html). Within that iframe.htm
page I have:
<a href="javascript:void(0);" onclick="window.parent.alertTest();">Click here.</a>
The problem is it is not loading the alert and in Google Chrome returns the error:
"Uncaught TypeError: Property 'alertTest' of object [object DOMWindow] is not a function
I have tried window.parent.alertTest();
, window.top.alertTest();
, top.alertTest();
, parent.alertTest();
and nearly everything that came up on similar problems I searched.
It seems you are unable to call a function located in a non-iframe, from the iframe located within said non-iframe.
Please help!
P.S. Essentially in the actual final outcome I'm trying to call a Lightbox open image function (Using slimbox because I am able to call the open image function with it from javascript rather than from a href). I have also tried in this final outcome using the target="_parent" property.
Try defining your function like this:
window.alertTest = function () {
alert("Testing");
};
...and calling it in the same way you have in the question ;-)
In a browser, everything in javascript is a child of the window
object. When you define a function in the form function funcName() { ... }
you are effectively defining a private method of the window
object. This doesn't matter under normal circumstances, because all code is executed within the scope of window
, so it has access to these private methods.
But when you try and access the window
object from the outside (i.e. another window
object, that of your iframe) you will not be allowed access to it. If you define the function in the form window.funcName = function () { ... };
you are creating a privileged method, that is accessible from the outside but also has access to the private methods and properties (i.e. the variables in the script), so it will work when you try and call it from your iframe.
Read this if you want to know more about private/privileged members and their accessibility.
use parent.functionName
. Check out this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With