如何在 iframe 标签中插入 javascript 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13643738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:21:18  来源:igfitidea点击:

How to insert javascript code in iframe tag

javascriptjqueryiframe

提问by mukund002

I am doing like this but not working:-

我这样做但不工作:-

I am trying to insert the pixel in iframe and then append it to the body.

我正在尝试在 iframe 中插入像素,然后将其附加到正文中。

jQuery('#subscribr').append('<iframe>
<script language="javascript" src="http://www.abc/static/st.v2.js"></script>
<script language="javascript">
var ef_event_type="transaction";
var ef_transaction_properties = "ev_ProductViews=1";
/*
 * Do not modify below this line
 */
var ef_segment = "";
var ef_search_segment = "";
var ef_userid="xxxx";
var ef_pixel_host="pixel.abc.net";
var ef_fb_is_app = 0;
effp();
</script>
</iframe>');
enter code here

回答by Cerbrus

Scripts like that appear to break when </script>is included in the string. A workaround to that could be to add the elements through dom manipulation:

</script>包含在字符串中时,像这样的脚本似乎会中断。解决方法可能是通过 dom 操作添加元素:

iframe = $('<iframe>');

var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "http://www.abc/static/st.v2.js"; // Or:
script.text  = "Your code here!"

iframe[0].appendChild(script);
iframe.appendTo('#subscribr'))

回答by mukund002

This is the solution which worked for me..

这是对我有用的解决方案..

var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "http://www.abc/static/st.v2.js";
    // Use selector here
    jQuery("#subscribr").append(s);

回答by Boris Gappov

Working sample: http://fiddle.jshell.net/f2x7G/

工作示例:http: //fiddle.jshell.net/f2x7G/

var doc = null;
   if(iframe.contentDocument) doc = iframe.contentDocument;
   else if(iframe.contentWindow) doc = iframe.contentWindow.document;
   else if(iframe.document) doc = iframe.document;

if(doc == null) throw "Document not initialized";

doc.open();
var script   = doc.createElement("script");
script.type  = "text/javascript";
// script.src = 'http://www.abc/static/st.v2.js';
script.text  = "alert('voila!');"
doc.appendChild(script);
doc.close();