如何在iframe中未定义的iFrame中运行代码?

时间:2016-02-24 01:37:03

标签: javascript jquery html css iframe

我需要运行代码,好像它在页面上的iframe中运行一样,这意味着当我在代码中使用window时,它应该使用iframe的window对象。它不是我创建的iframe,所以我的函数没有在其中定义。

var myfunction = function () { // defined in parent, not in the iframe
  console.log(window); // window here should be the iframe's window object, not the parent/
  window.document.body.appendChild("Appending to iframe body");
}

// Need to somehow run this function inside the iframe
myfunction(); // as if I did this inside the iframe

我需要在iframe中运行这个确切的代码,我知道我可以自己修复此问题

frames["FrameName"].document.body.appendChild("Appending to iframe body");

但这不会解决我的问题。

这是因为我自己没有编写代码,我使用了一个名为Opentip的模块来创建工具提示。我需要在iframe内的元素上设置工具提示;但是,Opentip使用其代码中的window对象才能正确创建工具提示。

所以我需要运行

Opentip(myelement, data);

好像我在iframe中运行它,但没有在iframe中定义它。

因此Opentip函数需要使用iframe窗口,而不是父窗口。

1 个答案:

答案 0 :(得分:0)

提供的代码当然未经测试。答案是假设:

  • OP情况是满足same origin policy的要求。
  • OP无法直接编辑子页面。
  • OP无法使用Ajax。

<强>资源

<强>段

&#13;
&#13;
//A//Ref to iframe
var iFrm = document.getElementById('iFrm')

//B//Listen for load event 
iFrm.addEventListener('load', function(e) {
  
  //C//Ref to iframe Window
  var iWin = iFrm.contentWindow;
  
  //D//Ref to iframe Document 
  var iDoc = iFrm.contentDocument? iFrm.contentDocument:iFrm.contentWindow.document;
  
  //E//Ref element targeted by Opentip--replace {{>SEL<}} with appropriate selector
  var iTgt = document.querySelector({{>SEL<}});
  
  //F//Create, configure, deploy, and inject <script> tag to iframe <head>
  var iNode = document.createElement(`script`);
  iNode.src = "https://cdn.jsdelivr.net/opentip/2.4.6/opentip-native.min.js";
  iDoc.head.appendChild(iNode); 
  
  //G//Call Opentip from iframe Window, and hopefully in iframe's context
  iFrm.contentWindow.Opentip = function(iTgt, data);
}
  
/* Notes */
/*//F//Alternative to target iframe <head>:
window.frames["iFrm"].document.getElementsByTagName("head")[0];*/
                      
   /*//If not successful in accuirring iframe, try replacing all
 "document." with "contentWindow", "contentDocument", or "contentWindow.document"*/
&#13;
<iframe id="iFrm" name="iFrm" src="/"></iframe>

<!--Optionally you can add an onload event to the iframe itself

<iframe id="iFrm" name="iFrm" src="/"></iframe>

-->
&#13;
&#13;
&#13;

相关问题