28

I have a WKWebView, but when I click on a link that has the following URL:

blob:https://www.mycase.com/2963c6c0-24c1-418f-a314-88f7a2dbc713

Nothing happens. Reading the documentation it describes:

The only way to read content from a Blob is to use a FileReader.

So I presume there is no way WKWebView is able to read the Blob itself by some method. As URLSession fails to download the content when you feed it the blob URL.

A solution I came up with myself is to read the blob in JavaScript itself.

var script = ""

script = script + "var xhr = new XMLHttpRequest();"
script = script + "xhr.open('GET', '\(navigationURL)', true);"
script = script + "xhr.responseType = 'blob';"
script = script + "xhr.onload = function(e) { if (this.status == 200) { var blob = this.response; var reader = new window.FileReader(); reader.readAsBinaryString(blob); reader.onloadend = function() { window.webkit.messageHandlers.readBlob.postMessage(reader.result); }}};"
script = script + "xhr.send();"

self.webView.evaluateJavaScript(script, completionHandler: nil);

Then add a script message handler to fetch the content.

let configuration = WKWebViewConfiguration()
configuration.userContentController.add(self, name: "readBlob")

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print(message.body)
}

It feels a bit cumbersome to do it like this, is there any other way?

Mark
  • 16,906
  • 20
  • 84
  • 117
  • Did you find any solution for this – Darshan Mothreja Feb 07 '19 at 11:47
  • Did you find solution? – Mickael Belhassen May 01 '20 at 07:01
  • @DarshanMothreja see if this helps you: https://stackoverflow.com/questions/61702414/wkwebview-how-to-handle-blob-url/61703086# – user120242 May 09 '20 at 21:13
  • For some reason the `didReceive message` callback does never get called. My blob looks very similar to your example. But your `script` does not seem to do the job. Can you please show more of your original workaround example ? Thank you – iKK Jan 17 '21 at 17:52
  • In fact, I can change the script to an example-script such as `window.webkit.messageHandlers.readBlob.postMessage('test');` and everything works. But your complicated Request-script still does not seem to work. Do you know if it will work for images or videos being downloaded ?? What was your original download type for your code script-example ? – iKK Jan 17 '21 at 18:10
  • Hello. Your example with script does not work. xhr.onload never called. Maybe you have another way? – runia Sep 02 '21 at 12:37
  • This has worked in the past (four years ago) if it doesn't know I am curious for a solution too. Sorry I can't help you any further. – Mark Sep 02 '21 at 14:24
  • Where is this blob: URL coming from? There's a lot of potential problems with URLs that have "blob:" as a scheme. – benc Mar 16 '23 at 20:25

0 Answers0