最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to insert javascript code in iframe tag - Stack Overflow

programmeradmin10浏览0评论

I am doing like this but not working:-

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

jQuery('#subscribr').append('<iframe>
<script language="javascript" src="/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";
var ef_fb_is_app = 0;
effp();
</script>
</iframe>');
enter code here

I am doing like this but not working:-

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

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
Share Improve this question asked Nov 30, 2012 at 10:51 mukund002mukund002 1231 gold badge2 silver badges15 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 9

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:

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

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

Working sample: 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();
发布评论

评论列表(0)

  1. 暂无评论