简体   繁体   English

如何将动态JavaScript代码注入到父页面上已经存在的iframe中

[英]How to inject dynamic javascript code into an iframe that already exists on parent page

I am trying to inject code into an iframe but I haven't had any luck and I'm not sure why. 我正在尝试将代码注入到iframe中,但是我没有任何运气,我不确定为什么。 I store my js code into a variable, which works properly at this point, into a variable called pixel_code. 我将js代码存储到一个变量中,该变量此时可以正常工作,并存储在一个名为pixel_code的变量中。 I then want to inject that code into the iframe. 然后,我想将该代码注入到iframe中。 Assuming the id of the iframe is "iframe_" how would I inject the code (variable is pixel_code) into the iframe and execute it? 假设iframe的ID为“ iframe_”,我该如何将代码(变量为pixel_code)注入iframe并执行它? I think jquery would be the easiest way, but I'm open to regular JS as well. 我认为jquery是最简单的方法,但是我也对常规JS开放。

One of my many unsuccessful attempts is: 我的许多失败尝试之一是:

function captureValue(){

pixel_code = document.getElementById("baseText").value;

$('#iframe_').find('body').append(pixel_code);

}

No errors are generated in the console. 控制台中不会生成任何错误。

Try using contents method: 尝试使用contents方法:

$('#iframe_').contents().find('body').append(pixel_code);

Note that domain of the iframe should match with the domain of the parent page, otherwise Same Origin Policy prevents accessing the iframe's contents. 请注意,iframe的域应与父页面的域匹配,否则,“ 相同来源策略”会阻止访问iframe的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM