【问题标题】:Pass parameter to BLOB object URL将参数传递给 BLOB 对象 URL
【发布时间】:2023-03-19 17:00:02
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你这样做的目的是什么?
  • 正如我所说:传递参数
  • 传一个参数来实现什么?
  • 我已经根据我的理解重写了您的问题;希望您不会再被否决 - 如果我的理解有误,请回滚

标签: javascript html blob parameter-passing


【解决方案1】:

如果您使用 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));

如果您可以将它们添加到根 &lt;HTML&gt; 标记作为属性或使用 &lt;BASE&gt; 元素作为 url 或将它们作为脚本标记插入,您也可以使用 HTML 执行此操作,但这需要您修改响应 HTML 而不是只是预先添加一些额外的数据

【讨论】:

    【解决方案2】:

    为了完整起见,如果您希望能够引用其中包含问号“查询字符串”指示符的 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")
        }
    }
    

    【讨论】:

    • 2021年还是这样吗?
    • 我帮不上忙,所以这取决于其他人。对不起。
    【解决方案3】:

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

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

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

    【讨论】:

    • 这在 Safari 中不起作用。 Safari 有什么解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多