Reputation: 53
Is it possible to execute inline JavaScript code on src attribute of an existing IFrame (function that do some logic and return an url ) ?
When I try the code, I get the error : Uncaught ReferenceError: hello is not defined
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<script type="text/javascript">
var hello = function(src1){
// some logic goes here
return "www.mysite.com";
}
</script>
</head>
<body>
<iframe width="400" height="400" src="javascript:hello()" >
</iframe>
</body>
</html>
Upvotes: 2
Views: 5456
Reputation: 91
The call to hello() is is executing inside the iframe ( because 'javascript:hello()' is the iframe SRC) But the function 'hello()' is declared outside the iframe in the parent window, in which the iframe is embedded. You can either call parent.hello() in your iframe src, or declare the body of hello() in the iframe src before calling hello(). The following demonstrates both methods :
<script>
var hello = function(){
alert('hello from outside the iframe');
}
</script>
<iframe width="400" height="400" src="javascript:var hello = function(){alert('hello from inside the iframe')};hello();parent.hello()"></iframe>
You can see it in action here: https://fiddle.jshell.net/vtdc1qxf/3/
Upvotes: 2
Reputation: 1935
You could use document.write
.
<body>
<script type="text/javascript">
document.write('<iframe width="400" height="400" src="' + hello() + '"></iframe>')
</script>
</body>
Upvotes: 0
Reputation: 4275
You can't put inline javascript in src attribute. You can use onload event for this. Use the code below
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<script type="text/javascript">
var hello = function(src1){
// some logic goes here
return "mysitename.com";
}
</script>
</head>
<body>
<iframe width="400" height="400" onload="this.src = hello()">
</iframe>
</body>
</html>
Hope this helps you
Upvotes: 1