How to read a blob data URL in WKWebView?

别来无恙 提交于 2019-12-04 18:09:42

问题


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?

来源:https://stackoverflow.com/questions/45065085/how-to-read-a-blob-data-url-in-wkwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!