在 IFrame src 属性中执行内联 JavaScript 代码

Execute Inline JavaScript code within IFrame src attribut

是否可以在现有 IFrame 的 src 属性上执行内联 JavaScript 代码(执行某些逻辑和 return 和 url 的函数)?

当我尝试代码时,出现错误: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>

您不能将内联 javascript 放在 src 属性中。您可以为此使用 onload 事件。使用下面的代码

<!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>

希望对您有所帮助

你可以使用 document.write.

<body>
  <script type="text/javascript">
    document.write('<iframe width="400" height="400" src="' + hello() + '"></iframe>')
  </script>
</body>

对 hello() 的调用正在 iframe 内执行(因为 'javascript:hello()' 是 iframe SRC) 但是函数 'hello()' 是在父 window 的 iframe 之外声明的,其中嵌入了 iframe。 您可以在 iframe src 中调用 parent.hello(),或者在调用 hello() 之前在 iframe src 中声明 hello() 的主体。下面演示了这两种方法:

<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>

您可以在此处查看实际效果: https://fiddle.jshell.net/vtdc1qxf/3/