Pass parameter to BLOB object URL

前端 未结 3 1021
醉话见心
醉话见心 2020-12-21 09:49

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

相关标签:
3条回答
  • 2020-12-21 10:15

    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")
        }
    }
    
    0 讨论(0)
  • 2020-12-21 10:16

    If you are doing this with a Javascript Blob for say a WebWorker then you can just to add the parameters into the Blob constructor as a global variable:

    const parameters = 'parameters = ' + JSON.stringify({foo:'bar'});
    const body = response.body; // From some previous HTTP request
    const blob = new Blob([parameters, body], { type: 'application/javascript' });
    new Worker(URL.createObjectURL(blob));
    

    Or more general case just store the original URL on the location object

    const location = 'location.originalHref = "' + url + '";';
    const body = response.body; // From some previous HTTP request
    const blob = new Blob([location, body], { type: 'application/javascript' });
    new Worker(URL.createObjectURL(blob));
    

    You could also do this with HTML if you can add them say to the root <HTML> tag as attributes or use the <BASE> element for the url or insert them as a script tag but this would require you to modify the response HTML rather then just prepend some extra data

    0 讨论(0)
  • 2020-12-21 10:27

    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/

    0 讨论(0)
提交回复
热议问题