iOS 12 Wkwebview Not Working with Redirects

Capture redirect url in wkwebview in ios

Use this WKNavigationDelegate method

public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
if(navigationAction.navigationType == .other) {
if let redirectedUrl = navigationAction.request.url {
//do what you need with url
//self.delegate?.openURL(url: redirectedUrl)
}
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}

Hope this helps

WKWebView - Add a parameter to the URL on redirect in Swift - iOS

WKNavigationDelegate, URLComponents

class ViewerViewController: UIViewController, WKNavigationDelegate  //<--
// then whenever you call the WKWebView
//ex: URL = https://en.wikipedia.org/wiki/Main_Page

WKWebView.navigationDelegate = self

WKWebView.load(URLRequest)

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

print("URL:", navigationAction.request.url)
if let host = navigationAction.request.url?.path
{
if host.contains("Main_Page")
{
//You can modify this part to form a new url and pass it again.
var components = URLComponents()
components.scheme = navigationAction.request.url?.scheme
components.host = navigationAction.request.url?.host
components.path = navigationAction.request.url!.path

print("new URL:", components.url!)
let customRequest = URLRequest(url: components.url!)

//change the url and pass it again..
WKWebView.load(customRequest) //<--load the new url again..
decisionHandler(.cancel)
}
else
{
decisionHandler(.allow) //<-- this will open the page.
}
}
else
{
decisionHandler(.allow)
}
}

Why is WKWebView not opening links with target=_blank?

My solution is to cancel the navigation and load the request with loadRequest: again. This will be come the similar behavior like UIWebView which always open new window in the current frame.

Implement the WKUIDelegate delegate and set it to _webview.uiDelegate. Then implement:

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
if (!navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
}

return nil;
}


Related Topics



Leave a reply



Submit