更改为IFRAME的内容。从另一个IFRAME将脚本注入IFRAME

时间:2014-07-30 09:31:43

标签: javascript parsing iframe inject

我正在编写一个脚本来获取和更改IFrame的内容,方法是通过按钮和在另一个IFrame中创建的Javascript脚本访问其中定义的变量和函数。该脚本工作正常,但我想做的是在IFRAME 1中注入文本而不是文本我想注入一个脚本,如:

<script src="map.js" type="text/javascript"></script>

我尝试过注入IMG并且也有效:

<button onclick="f_ifr2('<img height=\'410\' src=\'images\/footer.png\' width=\'995\' \/>')">

....但我希望能够注入一个类似于:

的js文件
<button onclick="f_ifr2('<script src=\'map.js\' type=\'text\/javascript\'><\/script>')">

但它不能用于关闭或打开标签&lt; &GT;

有人可以告诉我如何改写:

<button onclick="f_ifr2('<script src=\'map.js\' type=\'text\/javascript\'><\/script>')">

避免错误?非常感谢!

以下整个剧本:

代码ifr1.htm

<html>
<head>
<title>Page for IFrame 1</title>
<script type="text/javascript"><!--
// Stores a value in the variable "var_ifr1", that will be accessed in the second iframe
var var_ifr1 = '<b>Value of the variable from iframe 1</b>';

// Function that replace the content of the DIV "div_ifr1" with the value of its parameter
// It will be called from iframe 2
function f_ifr1(txt) {
  document.getElementById('div_ifr1').innerHTML = txt;
}
//--></script>
</head>
<body>
IFRAME 1
Content in BODY
<div id="div_ifr1">Div content of the iframe 1</div>
</body>
</html>

代码ifr2.htm

<html>
<head></head>
<title>Page for IFrame 2</title>
<body>
IFRAME 2<br>

<script type="text/javascript"><!--
function f_ifr2(txt) {
  // get the BODY content of the iframe 1, "ifr1"
  var c_ifr1 = parent.ifr1.document.body.innerHTML;

   alert(c_ifr1);          // Displays the content in an alert window

  // gets the value of the variable "var_ifr1", defined in the iframe 1, "ifr1"
  var from_ifr1 = parent.ifr1.var_ifr1;
  // Displays in a tag in this iframe the value of the variable defined in iframe 1
  document.getElementById('d_ifr2').innerHTML = from_ifr1;

  // Calls the function "f_ifr1",  defined in iframe 1
  parent.ifr1.f_ifr1(txt);
}
//--></script>
<div id="d_ifr2"> </div>
<button onclick="f_ifr2('<b>The text changed from iframe 2</b>')">Action iframe</button>
</body>
</html>

代码main.html

<html>
<head><title>Main Page</title></head>
<body>
<h3>Main Page</h3>
<h4>First iframe</h4>
<iframe src="ifr1.htm" id="ifr1" name="ifr1"></iframe>

<br><h4>Second iframe</h4>
<iframe src="ifr2.htm" id="ifr2" name="ifr2"></iframe>
</body>
</html>

0 个答案:

没有答案