How can I access a blob from one domain to other on CLIENT side
Asked Answered
R

1

11

Lets say I have two domains

  • abc.com
  • xyz.com

I am receiving a blob from server (lets say on abc.com) and thats how I get the url of that blog:

    var pdfFile = new Blob([(blob)], {type: 'application/pdf'});
    var fileURL = URL.createObjectURL(this.pdfFile);
    this.url = fileURL;

Now I have url and all I want is to access that blob from one of my other website (xyz.com) which is hosted on another domain.

When I get the blob in abc.com I open my other website xyz.com in new tab in such way that it has the link of blob. But how can I access that blob using that link?

Currently I am trying this on xyz.com:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'blob:http%3A//abc.com', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
  if (this.status == 200) {
    var myBlob = this.response;
  }
};
xhr.send();

But its giving my error, and ofcourse it is supposed to because of different domains

Failed to load blob:http://myBlobFullURL Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Rawlings answered 5/7, 2018 at 9:3 Comment(1)
are you opening xyz.com using window.open?Vinasse
E
5

Because of StackExchange rules, abc.com was replaced with example.com and xyz.com was replaced with example.net (read more).

blob URLs cannot be accessed cross-domain, the workaround is to postMessage the Blob object (read more).

At example.com :

const exampleDotNet = window.open('https://example.net');
// TODO wait for example.net to be ready
exampleDotNet.postMessage(pdfFile, 'https://example.net');

At example.net :

window.addEventListener(
    'message',
    ({
        origin,
        data: myBlob
    }) => {
        if(origin === 'https://example.com'){
            // TODO something with myBlob
        }
    }
);
Ezekielezell answered 17/8, 2022 at 8:27 Comment(5)
great solution, I have one question regarding this. Would this approach be necessary if the target domain is a subdomain of the sender?Scherer
Maybe not, try opening a domain's blob: URL from a subdomain of it, and see if an error is thrown.Ezekielezell
blob url didn't end up working when attempted to access through subdomain with the error message Not allowed to load local resource: blob:subdomain/[BLOD_ID]Scherer
a follow up question I have is the --to do part you have here? how would you go about waiting the example.net to be ready and at least have the eventlistener set ? I tried putting onload listener to the new window ref but also wasn't allowed due to cors rules, I guess an unreliable set timeout is the only way even though it is quite unreliable?Scherer
When example.net is ready, you postMessage from it to example.com.Ezekielezell

© 2022 - 2024 — McMap. All rights reserved.