简体   繁体   English

如何在iframe中调用javascript函数

[英]how to call a javascript function inside an iframe

Please, i need to include an iframe in an html document, but need also to push a variable from a Js function located on the same page (which retrieve cookies values) 请,我需要在html文档中包含一个iframe,但是还需要从位于同一页面上的Js函数(检索cookie值)中推送一个变量

<script type=text/JavaScript>
var generateLinkerUrl = function(url){ etc...
  </script>
<body>

<iframe src=
var newUrl =
generateLinkerUrl("http://blog.domain.com/mypage.php") // url of the iframe </iframe>`  

Is the call to the Js function inside the tag correct or do i need something else to add ? 标记内对Js函数的调用是否正确,还是我需要添加其他内容?

Many tks.. 很多tks ..

You can't put a javscript function inside an iframe tag like it looks like you are attempting. 您无法将javscript函数放在iframe代码中,就像您正在尝试的那样。 It is not entirely clear what you are trying to accomplish, but here is some info: 尚不清楚您要完成什么,但是这里有一些信息:

If the iframe is not on the same domain as the host document, then the browser will block all direct javascript access between the two except for cooperating communication using [window.postMessage()][1] . 如果iframe与主机文档不在同一域中,则浏览器将阻止两者之间的所有直接javascript访问,除了使用[window.postMessage()][1]进行协作通信之外。

If the iframe is on the same domain as the host document, then you can reach inside the document of the iframe like this: 如果iframe与主机文档位于同一域中,则可以像下面这样进入iframe文档:

// iframe is the DOM element of the iframe from the host document
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

Then, from that, you can get to the window which lets you get to global javascript variables or functions. 然后,您可以从该窗口进入到全局javascript变量或函数的窗口。

Putting that all together, you could call a function in an iframe on the same domain like this: 将所有内容放在一起,您可以像这样在同一域的iframe中调用函数:

var iframe = document.getElementById("myIframe");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var iframeWindow = iframeDocument.window;

// call function in the iFrame
iframeWindow.funcIniFrame("xxx");

If, what you're really trying to do is to have an iframe with a .src attribute that is generated from the host document, you can do that like this and there are no domain restrictions for this type of setting: 如果您真正想做的是拥有一个从宿主文档生成的具有.src属性的iframe,则可以这样做,并且这种设置没有域限制:

<iframe id="myIFrame"></iframe>

<script>
document.getElementById("myIFrame").src = generateLinkerUrl("http://blog.domain.com/mypage.php");
</script>

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

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