当前位置 : 首页 » 互动问答 » 正文

Alternative to iFrames with HTML5

分类 : 互动问答 | 发布时间 : 2012-01-02 23:46:51 | 评论 : 12 | 浏览 : 369238 | 喜欢 : 140

I would like to know if there is an alternative to iFrames with HTML5. I mean by that, be able able to inject cross-domains HTML inside of a webpage without using an iFrame.

回答(12)

  • 1楼
  • Basically there are 4 ways to embed HTML into a web page:

    • <iframe> An iframe's content lives entirely in a separate context than your page. While that's mostly a great feature and it's the most compatible among browser versions, it creates additional challenges (shrink wrapping the size of the frame to its content is tough, insanely frustrating to script into/out of, nearly impossible to style).
    • AJAX. As the solutions showed here prove, you can use the XMLHttpRequest object to retrieve data and inject it to your page. It is not ideal because it depends on scripting techniques, thus making the execution slower and more complex, among other drawbacks.
    • Hacks. Few mentioned in this question and not very reliable.
    • HTML5 Web Components. HTML Imports, part of the Web Components, allows to bundle HTML documents in other HTML documents. That includes HTML, CSS, JavaScript or anything else an .html file can contain. This makes it a great solution with many interesting use cases: split an app into bundled components that you can distribute as building blocks, better manage dependencies to avoid redundancy, code organization, etc. Here is a trivial example:

      <!-- Resources on other origins must be CORS-enabled. -->
      <link rel="import" href="http://example.com/elements.html">
      

    Native compatibility is still an issue, but you can use a polyfill to make it work in evergreen browsers Today.

    You can learn more here and here.

  • 2楼
  • No, there isn't an equivalent. The <iframe> element is still valid in HTML5. Depending on what exact interaction you need there might be different APIs. For example there's the postMessage method which allows you to achieve cross domain javascript interaction. But if you want to display cross domain HTML contents (styled with CSS and made interactive with javascript) iframe stays as a good way to do.

  • 3楼
  • You can use object and embed, like so:

    <object data="http://www.web-source.net" width="600" height="400">
        <embed src="http://www.web-source.net" width="600" height="400"> </embed>
        Error: Embedded data could not be displayed.
    </object>
    

    Which isn't new, but still works. I'm not sure if it has the same functionality though.

  • 4楼
  • object is an easy alternative in HTML5:

    <object data="https://blogs.claritycon.com/blog/2016/03/bower-packages-asp-net-core-1-0/" width="400" height="300" type="text/html">
        Alternative Content
    </object>

    You can also try embed:

    <embed src="https://blogs.claritycon.com/blog/2016/03/bower-packages-asp-net-core-1-0/" width=200 height=200 />

  • 5楼
  • If you want to do this and control the server from which the base page or content is being served, you can use Cross Origin Resource Sharing (http://www.w3.org/TR/access-control/) to allow client-side JavaScript to load data into a <div> via XMLHttpRequest():

    // I safely ignore IE 6 and 5 (!) users
    // because I do not wish to proliferate
    // broken software that will hurt other
    // users of the internet, which is what
    // you're doing when you write anything
    // for old version of IE (5/6)
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if(xhr.readyState == 4 && xhr.status == 200) {
        document.getElementById('displayDiv').innerHTML = xhr.responseText;
      }
    };
    xhr.open('GET', 'http://api.google.com/thing?request=data', true);
    xhr.send();
    

    Now for the lynchpin of this whole operation, you need to write code for your server that will give clients the Access-Control-Allow-Origin header, specifying which domains you want the client-side code to be able to access via XMLHttpRequest(). The following is an example of PHP code you can include at the top of your page in order to send these headers to clients:

    <?php
      header('Access-Control-Allow-Origin: http://api.google.com');
      header('Access-Control-Allow-Origin: http://some.example.com');
    ?>
    
  • 7楼
  • An iframe is still the best way to download cross-domain visual content. With AJAX you can certainly download the HTML from a web page and stick it in a div (as others have mentioned) however the bigger problem is security. With iframes you'll be able to load the cross domain content but won't be able to manipulate it since the content doesn't actually belong to you. On the other hand with AJAX you can certainly manipulate any content you are able to download but the other domain's server needs to be setup in such a way that will allow you to download it to begin with. A lot of times you won't have access to the other domain's configuration and even if you do, unless you do that kind of configuration all the time, it can be a headache. In which case the iframe can be the MUCH easier alternative.

    As others have mentioned you can also use the embed tag and the object tag but that's not necessarily more advanced or newer than the iframe.

    HTML5 has gone more in the direction of adopting web APIs to get information from cross domains. Usually web APIs just return data though and not HTML.

  • 8楼
  • You can use an XMLHttpRequest to load a page into a div (or any other element of your page really). An exemple function would be:

    function loadPage(){
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("ID OF ELEMENT YOU WANT TO LOAD PAGE IN").innerHTML=xmlhttp.responseText;
        }
    }
    
    xmlhttp.open("POST","WEBPAGE YOU WANT TO LOAD",true);
    xmlhttp.send();
    }
    

    If your sever is capable, you could also use PHP to do this, but since you're asking for an HTML5 method, this should be all you need.

  • 9楼
  • I created a node module to solve this problem node-iframe-replacement. You provide the source URL of the parent site and CSS selector to inject your content into and it merges the two together.

    Changes to the parent site are picked up every 5 minutes.

    var iframeReplacement = require('node-iframe-replacement');
    
    // add iframe replacement to express as middleware (adds res.merge method) 
    app.use(iframeReplacement);
    
    // create a regular express route 
    app.get('/', function(req, res){
    
        // respond to this request with our fake-news content embedded within the BBC News home page 
        res.merge('fake-news', {
            // external url to fetch 
           sourceUrl: 'http://www.bbc.co.uk/news',
           // css selector to inject our content into 
           sourcePlaceholder: 'div[data-entityid="container-top-stories#1"]',
           // pass a function here to intercept the source html prior to merging 
           transform: null
        });
    });
    

    The source contains a working example of injecting content into the BBC News home page.

  • 10楼
  • you can use object tag This also does seem to work

  • 11楼
  • Although there isn't any perfect replacement I have been working on something, it's built be-be easy and I'm happy to say it works (thanks to junkfoodjunkie)

    Basically, my current system uses some basic php/server combo to load and then save the file to the server, I just started up the project today so only the main file (such as index.html) is loaded. I'll be working to make it load 50 ish links from the page to help with support. If you would like to test it: it is hosted here. To use it is easy, just load the URL http://integratedmedia.ml/get/?link= and add your page to the end. no need to add in https or www. It will also cause problems if you do :) Anyways if you follow that set your copied page will be found at integratedmedia.ml/get/gettmp/YOURURL.html. Here is an example:

    integratedmedia.ml/get/?link=google.com

    the downloaded file is now at

    integratedmedia.ml/get/gettmp/google.com.html

  • 12楼
  • <object data="https://blogs.claritycon.com/blog/2016/03/bower-packages-asp-net-core-1-0/" width="400" height="300" type="text/html">
        Alternative Content
    </object>

相关阅读:

Resize HTML5 canvas to fit window

Adjust width and height of iframe to fit with content in it

Sound effects in JavaScript / HTML5

HTML text input allows only numeric input

HTML 5: Is it <br>, <br/>, or <br />?

How do I make a placeholder for a 'select' box?

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

What is the max size of localStorage values?

EMBED vs. OBJECT

Using HTML5 file uploads with AJAX and jQuery