How to add JavaScript code into existing iFrame us

2019-02-01 23:43发布

I want to add a JavaScript snippet into an existing iFrame in the page using jQuery. I have the following code...

Code:

content = "<script>" + js_code + "</script>";

$('#iframe_id').contents().find('body').append(content);

But somehow this is not working. I checked some of the existing/related answers, and it seems jQuery does not quite recognize the script tags as...script tags. The iFrame is in the same domain/same port/same host, so there is no issue about cross-site scripting etc. How can I fix this?

8条回答
萌系小妹纸
2楼-- · 2019-02-02 00:41

I cannot comment to your last post, because i'm new here and i dont have enough reputation but like i said in my post the problem was in the /script.

So escaping it ( like google does for instance ) maybe is the best option...

Well, the good news is that the problem is solved ;)

Regards

查看更多
唯我独甜
3楼-- · 2019-02-02 00:45
var script = "alert('hello world');";
$('#iframe').contents().find('body').append($('<script>').html(script))

works in Fiddle

查看更多
登录 后发表回答