set a Blob as the “src” of an iframe

柔情痞子 提交于 2021-02-06 10:16:47

问题


The following code work perfectly in Chrome

<script>
function myFunction() {
var blob = new Blob(['<a id="a"><b id="b">hey!</b></a>'], {type : 'text/html'});
var newurl = window.URL.createObjectURL(blob);
    document.getElementById("myFrame").src = newurl;
}
</script>

But it is not working with IE. Can some one please tell me what is wrong here.

The iframe "src" also set to the blob as shown below.

<iframe id="myFrame" src="blob:0827B944-D600-410D-8356-96E71F316FE4"></iframe>

Note: I went on the window.navigator.msSaveOrOpenBlob(newBlob) path as well but no luck so far.


回答1:


According to http://caniuse.com/#feat=datauri IE 11 has only got partial support for Data URI's. It states support is limited to images and linked resources like CSS or JS, not HTML files.

Non-base64-encoded SVG data URIs need to be uriencoded to work in IE and Firefox as according to this specification.




回答2:


I've run into the same problem with IE. However, I've been able to get the download/save as piece working in IE 10+ using filesaver.js.

function onClick(e) {
    var data = { x: 42, s: "hello, world", d: new Date() },
    fileName = "my-download.json";
    var json = JSON.stringify(data),
        blob = new Blob([json], {type: "octet/stream"});

   saveAs(blob, fileName);      

   e.preventDefault();
   return false;
};

$('#download').click(onClick);

See http://jsfiddle.net/o0wk71n2/ (based on answer by @kol to JavaScript blob filename without link)




回答3:


An example I did for Blob as a source of iFrame and working great with one important CAUTION / WARNING:

const blobContent = new Blob([getIFrameContent()], {type: "text/html"});
var iFrame = document.createElement("iframe");
iFrame.src = URL.createObjectURL(blobContent);
parent.appendChild(iFrame);

iFrame with Blob is not auto redirect protocol, meaning, having <script src="//domain.com/script.js"</script> inside the iframe head or body won't load the JS script at all even on Chrome 61 (current version).

it doesn't know what to do with source "blob" as protocol. this is a BIG warning here.

Solution: This code will solve the issue, it runs mostly for VPAID ads and working for auto-protocol:

function createIFrame(iframeContent) {
    let iFrame = document.createElement("iframe");
    iFrame.src = "about:blank";
    iFrameContainer.innerHTML = ""; // (optional) Totally Clear it if needed
    iFrameContainer.appendChild(iFrame);

    let iFrameDoc = iFrame.contentWindow && iFrame.contentWindow.document;
    if (!iFrameDoc) {
    console.log("iFrame security.");
    return;
    }
    iFrameDoc.write(iframeContent);
    iFrameDoc.close();
}


来源:https://stackoverflow.com/questions/29667922/set-a-blob-as-the-src-of-an-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!