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.

ykaragol
  • 6,139
  • 3
  • 29
  • 56
Zohab Ali
  • 8,426
  • 4
  • 55
  • 63

1 Answers1

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
        }
    }
);
KaKi87
  • 915
  • 7
  • 15
  • great solution, I have one question regarding this. Would this approach be necessary if the target domain is a subdomain of the sender? – Saccarab Mar 23 '23 at 15:15
  • Maybe not, try opening a domain's `blob:` URL from a subdomain of it, and see if an error is thrown. – KaKi87 Mar 24 '23 at 18:32
  • 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] – Saccarab Apr 04 '23 at 12:11
  • 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? – Saccarab Apr 05 '23 at 11:58
  • 1
    When `example.net` is ready, you `postMessage` from it to `example.com`. – KaKi87 Apr 05 '23 at 15:59