iframe跨域问题

发布于 2025-01-07 23:27:54 字数 308 浏览 0 评论 0原文

假设我有一个名为 example.com 的网站,其中 iframe 嵌入了 iframe.net 域,现在我想读取 iframe 的内容并传递一些参数来显示文本消息。喜欢用用户名嗨。

现在的问题是这无法在两者之间建立连接,甚至无法获取我使用以下方法的 iframe 的innerHTML

document.getElementById('myframe').contentWindow.document.body.innerHTML;

它会抛出错误“权限被拒绝访问属性”

有人知道如何在跨域中读写平台

For say i have a Site called example.com on which iframe is embedded of domain iframe.net, now i want to read the content of iframe and pass some parameter to display a textual message. Like Hi with username.

Now the problem is this able not able to make connection between the two , even am not able to get the innerHTML of iframe i used following approach

document.getElementById('myframe').contentWindow.document.body.innerHTML;

It throws error "Permission denied to access property"

Do anyone know how to read and write in cross domain platform

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

顾冷 2025-01-14 23:27:54

如果您无法控制被框架的网站,则无法规避跨域策略。

如果您可以控制这两个站点,则可以使用 postMessage 方法跨不同域传输数据。一个非常基本的例子:

// framed.htm:
window.onmessage = function(event) {
    event.source.postMessage(document.body.innerHTML, event.origin);
};

// Main page:
window.onmessage = function(event) {
    alert(event.data);
};

// Trigger:
// <iframe id="myframe" src="framed.htm"></iframe>
document.getElementById('myframe').contentWindow.postMessage('','*');

If you don't have control over the framed site, you cannot circumvent the cross-domain policy.

If you have control over both sites, you can use the postMessage method to transfer data across different domains. A very basic example:

// framed.htm:
window.onmessage = function(event) {
    event.source.postMessage(document.body.innerHTML, event.origin);
};

// Main page:
window.onmessage = function(event) {
    alert(event.data);
};

// Trigger:
// <iframe id="myframe" src="framed.htm"></iframe>
document.getElementById('myframe').contentWindow.postMessage('','*');
oО清风挽发oО 2025-01-14 23:27:54

Internet Explorer 8中,作为参数传递的事件可能为null,这就是为什么您需要以不同的方式访问事件:

frame.html< /strong>:

window.onmessage = function(event) {
   var evt = event || window.event;
   evt.source.postMessage('Message from iFrame', evt.origin);
};

ma​​in.html 上:

window.onmessage = function(event) {
   var evt = event || window.event;
   alert(evt.data);
};

事件的触发方式与 Rob W 介绍的方式相同:

document.getElementById('frameId').contentWindow.postMessage('message','*');

In Internet Explorer 8, events passed as a parameter may be null, that is why you need to access the event in a different manner:

In frame.html:

window.onmessage = function(event) {
   var evt = event || window.event;
   evt.source.postMessage('Message from iFrame', evt.origin);
};

On main.html:

window.onmessage = function(event) {
   var evt = event || window.event;
   alert(evt.data);
};

The event is triggered the same way as Rob W has presented:

document.getElementById('frameId').contentWindow.postMessage('message','*');
蒲公英的约定 2025-01-14 23:27:54

仅当您可以控制两个

可以使用的网站时,才会发生这种情况 postMessage

这是您首先应用它的方法

,您可以将以下代码添加到您要从中检索数据的网站

 <script>
        function test() {       
 document.getElementById('idMyIframe').contentWindow.postMessage("your message here", "*");
        }
    </script>
    <iframe id="idMyIframe" onload="test()" src="http://example.otherdomaintosenddatato.com"></iframe>

第二步,您可以将此代码添加到您想要向其发送消息或数据的其他域

 window.addEventListener("message", function (message) {
        if (message.origin == "http://firstdomain.com") {
            console.log(message)
        }
    });

请注意,您必须在 iframe 的 onload 属性上添加 test() 函数,因为如果该函数在 iframe 加载之前运行,它将变得无用,并且不会发送数据

It can happen only if you have control for both sites

you can use postMessage

here's how you can apply it

first, you can add the below code to the site you want to retrieve data from

 <script>
        function test() {       
 document.getElementById('idMyIframe').contentWindow.postMessage("your message here", "*");
        }
    </script>
    <iframe id="idMyIframe" onload="test()" src="http://example.otherdomaintosenddatato.com"></iframe>

the second step you can add this code below to the other domain you want to send a message or the data to it

 window.addEventListener("message", function (message) {
        if (message.origin == "http://firstdomain.com") {
            console.log(message)
        }
    });

and please note you must add the test() function on the onload attribute of the iframe cause if the function runs before the iframe was loaded it will become useless and it won't send data

梦一生花开无言 2025-01-14 23:27:54

React 中的跨域 iframe 元素访问 (srcDoc):-

<iframe srcDoc={this.state.HTML}  width='100%' id='iframetnd' onLoad={this.onclickinsideiframe}/>


 onclickinsideiframe=()=>{
      if(document.getElementById('iframetnd')!==null){

                let iframe = document.getElementById('iframetnd');

                let innerDocument = (iframe.contentDocument)  
                                   ? iframe.contentDocument 
                                   : iframe.contentWindow.document;
                let Obj = innerDocument.getElementsByClassName("navButtons")[0];
                    if(Obj !== undefined){
                        Obj.onclick = ()=>this.func();
          }
       }
    }



  func=()=>{
           this.setState({page:2})
           this.arrangeTest();
        }

Cross Domain iframe elements access in React with (srcDoc):-

<iframe srcDoc={this.state.HTML}  width='100%' id='iframetnd' onLoad={this.onclickinsideiframe}/>


 onclickinsideiframe=()=>{
      if(document.getElementById('iframetnd')!==null){

                let iframe = document.getElementById('iframetnd');

                let innerDocument = (iframe.contentDocument)  
                                   ? iframe.contentDocument 
                                   : iframe.contentWindow.document;
                let Obj = innerDocument.getElementsByClassName("navButtons")[0];
                    if(Obj !== undefined){
                        Obj.onclick = ()=>this.func();
          }
       }
    }



  func=()=>{
           this.setState({page:2})
           this.arrangeTest();
        }
墟烟 2025-01-14 23:27:54

iFrame 不允许跨域平台访问内容。仅当您的 iFrame 使用相同的域时才可以访问。

该解决方案的工作原理与 iFrame 相同。我创建了一个 PHP 脚本,可以从其他网站获取所有内容,最重要的部分是您可以轻松地将自定义 jQuery 应用于该外部内容。请参考以下脚本,可以从其他网站获取所有内容,然后您也可以应用您自定义的 jQuery/JS。该内容可以在任何地方、任何元素或任何页面内使用。

<div id='myframe'>

  <?php 
   /* 
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame(); 
  ?>

</div>

<?php

/* 
  Function to display frame from another domain 
*/

function displayFrame()
{
  $webUrl = 'http://[external-web-domain.com]/';

  //Get HTML from the URL
  $content = file_get_contents($webUrl);

  //Add custom JS to returned HTML content
  $customJS = "
  <script>

      /* Here I am writing a sample jQuery to hide the navigation menu
         You can write your own jQuery for this content
      */
    //Hide Navigation bar
    jQuery(\".navbar.navbar-default\").hide();

  </script>";

  //Append Custom JS with HTML
  $html = $content . $customJS;

  //Return customized HTML
  return $html;
}

iFrame does not allow to access contents from Cross Domain platform. You can only access if your iFrame is using the same domain.

This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.

<div id='myframe'>

  <?php 
   /* 
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame(); 
  ?>

</div>

<?php

/* 
  Function to display frame from another domain 
*/

function displayFrame()
{
  $webUrl = 'http://[external-web-domain.com]/';

  //Get HTML from the URL
  $content = file_get_contents($webUrl);

  //Add custom JS to returned HTML content
  $customJS = "
  <script>

      /* Here I am writing a sample jQuery to hide the navigation menu
         You can write your own jQuery for this content
      */
    //Hide Navigation bar
    jQuery(\".navbar.navbar-default\").hide();

  </script>";

  //Append Custom JS with HTML
  $html = $content . $customJS;

  //Return customized HTML
  return $html;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文