Okacha Ilias
Okacha Ilias

Reputation: 53

Execute Inline JavaScript code within IFrame src attribut

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

Answers (3)

Steve Thorpe
Steve Thorpe

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

Sildoreth
Sildoreth

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

Utkarsh Dixit
Utkarsh Dixit

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

Related Questions