将参数传递给 BLOB 对象 URL

Pass parameter to BLOB object URL

本文关键字:对象 URL BLOB 参数传递      更新时间:2023-09-26

>假设我有一个对 html 文件的引用作为 Blob b,我为它创建了一个 URL,url = URL.createObjectURL(b); .

这给了我一些看起来像blob:http%3A//example.com/a0440b61-4850-4568-b6d1-329bae4a3276

然后我尝试在带有 GET 参数?foo=bar<iframe>中打开它,但它不起作用。如何传递参数?

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>

演示

我不认为将查询字符串添加到 url 会起作用,因为它本质上将其更改为不同的 url。
但是,如果您只想传递参数,则可以使用哈希将片段添加到 url

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

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

为了完整起见,如果您希望能够引用带有问号"查询字符串"指示符的 blob,您可以在 Firefox 中选择任何方式,例如: blob:lalalal?thisworksinfirefox

对于 Chrome,上述操作将不起作用,但这将:blob:lalalla#?thisworksinchromeandfirefox

对于 Safari 和 Microsaft,没有什么真正有效,所以像这样做一个预测试,然后相应地计划:

 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")
    }
}

如果你使用 Javascript Blob 来做这件事,比如 WebWorker ,那么你可以将参数作为全局变量添加到 Blob 构造函数中:

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));

或者更一般的情况只是将原始URL存储在位置对象上

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));
您也可以使用 HTML 执行此操作,如果

您可以将它们作为属性添加到根 <HTML> 标记中,或者使用 url 的 <BASE> 元素或将它们作为脚本标记插入,但这需要您修改响应 HTML,而不仅仅是在前面附加一些额外的数据