2017年6月4日 星期日


Ref : https://stackoverflow.com/questions/31988121/facebook-login-button-does-not-work-within-wkwebview

func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    // A nil targetFrame means a new window (from Apple's doc)
    if (navigationAction.targetFrame == nil) {
        // Let's create a new webview on the fly with the provided configuration, 
        // set us as the UI delegate and return the handle to the parent webview
        let popup = WKWebView(frame: self.view.frame, configuration: configuration)
        popup.UIDelegate = self
        self.view.addSubview(popup)
        return popup
    }
    return nil;
}


ow that this is done, the new request will automatically be loaded in the "popup" WKWebView that was just created. The next step is to make sure to close it once the flow is done. Since we registered self as the popup.UIDelegate, we can remove the view when it will be closed by the external authentication flow:

func webViewDidClose(webView: WKWebView) {
    // Popup window is closed, we remove it
    webView.removeFromSuperview()
}

webwebview could show alert windows

Ref :   https://stackoverflow.com/questions/34185339/wkwebview-javascript-confirm-and-alert-not-working


import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

    var wkWebView: WKWebView!

    public override func viewDidLoad() {
        super.viewDidLoad()

        wkWebView = WKWebView(frame: view.bounds, configuration: WKWebViewConfiguration())
        wkWebView.uiDelegate = self
        wkWebView.navigationDelegate = self
        view.addSubview(wkWebView!)
        let url = URL(string: "https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert")!
        wkWebView.load(URLRequest(url: url))
    }

    func webView(_ webView: WKWebView,
                 runJavaScriptAlertPanelWithMessage message: String,
                 initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping () -> Void) {

        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        let title = NSLocalizedString("OK", comment: "OK Button")
        let ok = UIAlertAction(title: title, style: .default) { (action: UIAlertAction) -> Void in
            alert.dismiss(animated: true, completion: nil)
        }
        alert.addAction(ok)
        present(alert, animated: true)
        completionHandler()
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        wkWebView.evaluateJavaScript("alert('Hello from evaluateJavascript()')", completionHandler: nil)
    }
}