How to get the download attribute from WKWebView?

Viewed 490

Some anchors may have a download attribute with or without a filename specified (Link). How do you retrieve this filename within func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)?

1 Answers

It seems like none of the parameters webview and navigationAction do expose the value of the download attribute of the anchor tag clicked.

I solved this by calling webview.evaluateJavascript() executing document.querySelector() by the href attribute that we received from navigationAction.request.url.absoluteString:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

    webView.evaluateJavaScript("document.querySelector('[href=\"" + navigationAction.request.url.absoluteString + "\"]').download") {(result, error) in

        let fileName = result as? String ?? "FALLBACK DEFAULT NAME.csv"

        ...

    }

}
Related