Pass parameter to BLOB object URL

你。 提交于 2019-12-31 02:19:33

问题


Say I've got a reference to a html file as a Blob b and I create a URL for it, url = URL.createObjectURL(b);.

This gives me something that looks like blob:http%3A//example.com/a0440b61-4850-4568-b6d1-329bae4a3276

I then tried opening this in an <iframe> with a GET parameter ?foo=bar, but it didn't work. How can I pass the parameter?

var html ='<html><head><title>Foo</title></head><body><script>document.body.textContent = window.location.search<\/script></body></html>',
    b = new Blob([html], {type: 'text/html'}),
    url = URL.createObjectURL(b),
    ifrm = document.createElement('iframe');
ifrm.src = url + '?foo=bar';
document.body.appendChild(ifrm);

// expect to see ?foo=bar in <iframe>

DEMO


回答1:


I don't think adding a query string to the url will work as it essentially changes it to a different url.
However if you simply want to pass parameters you can use the hash to add a fragment to the url

ifrm.src = url + '#foo=bar';

http://jsfiddle.net/thpf584n/1/




回答2:


For completeness sake, if you want to be able to reference a blob that has as question mark "query string" indicator in it, you can do so in Firefox any way you choose, such as: blob:lalalal?thisworksinfirefox

For Chrome, the above will not work, but this will: blob:lalalla#?thisworksinchromeandfirefox

And for Safari and Microsaft, nothing really works, so do a pre test like so, then plan accordingly:

 function initScriptMode() {
  var file = new Blob(["test"], {type: "text/javascript"});
  var url = URL.createObjectURL(file) + "#test?test";

   var request = new XMLHttpRequest();
    request.responseType = responseType || "text";
    request.open('GET', url);


    request.onload = function() {
        alert("you can use query strings")
    };

    try {
        request.send(); 
    }
    catch(e) {
        alert("you can not use query strings")
    }
}


来源:https://stackoverflow.com/questions/27581335/pass-parameter-to-blob-object-url

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