2015-03-13 20 views
2

是否可以在現有IFrame的src屬性上執行內聯JavaScript代碼(執行一些邏輯並返回url的函數)?在iframe中執行內聯JavaScript代碼src attribut

當我嘗試的代碼,我得到的錯誤:未捕獲的ReferenceError:你好沒有定義

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <title>title</title> 
 
\t <script type="text/javascript"> 
 
\t \t var hello = function(src1){ 
 
      // some logic goes here 
 
\t \t \t return "www.mysite.com"; 
 
\t \t } \t 
 
\t </script> 
 
</head> 
 
<body> 
 
\t 
 
\t <iframe width="400" height="400" src="javascript:hello()" > \t 
 
\t </iframe> 
 
\t 
 
</body> 
 
</html>

+1

你必須設置src屬性的不同方式。 – 2015-03-13 17:05:39

+0

我知道可以獲取iframe HTMLElement並動態設置其src。我正在尋找最小的方式來完成相同的任務。 – 2015-03-13 17:42:54

回答

2

你不能把內嵌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> 

希望這段代碼可以幫助您

+0

謝謝,這是非常接近我需要的,我需要你好來阻止加載的iframe(空白內容),直到函數hello返回一些結果(外部ajax調用)。有ondomcontentloaded監聽器的iframes? – 2015-03-13 17:19:43

+0

如果要在ajax調用之後插入url,而不是在ajax的響應結果中插入document.getElementById(「iframeid」)。src =「您的URL」。它應該正常工作 – 2015-03-13 17:23:58

+0

這會導致無限循環,我認爲當iframe加載它時會更改它的src並重新加載,無限觸發onload。 – 2015-03-13 17:25:54

0

你可以使用document.write

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

雖然,我認爲@Hudixt發佈的解決方案可能更好。只是提供一個替代品。 – Sildoreth 2015-03-13 17:21:23

+0

不幸的是,我沒有太多的iframe控制,iframes已經出現在頁面上,我只能添加屬性(這是我可以做的最大改變)。 – 2015-03-13 17:31:23

+0

@ user3075416您可否將此添加到未來人的原始問題中,以查看他們是否偶然發現了您的問題? – Sildoreth 2015-03-13 17:36:23

0

爲hello(呼叫)是在iframe中執行(因爲 '的javascript:你好()' 是IFRAME SRC) 但功能 '你好()' 聲明父iframe的外窗口,其中嵌入了iframe。 您可以在調用hello()之前,在iframe src中調用parent.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/