Swift中的UIWebView和JavaScriptInterface

Pho*_*ocs 8 uiwebview ios swift

如何从我的网站创建JavascriptInterface频道到我的UIWebView?

Android中的示例:

webView.addJavascriptInterface(new WebAppInterface(this), "Android");
Run Code Online (Sandbox Code Playgroud)

从这个JavascriptInterface我想绘制方法,例如:

func webViewDidStartLoad(webView: UIWebView)
Run Code Online (Sandbox Code Playgroud)

要么

myActivityIndicator.startAnimating()
Run Code Online (Sandbox Code Playgroud)

我能怎么做?

Pho*_*ocs 16

对于WKWebView:源在这里

JavaScript的

function callNativeApp () {
    try {
            webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");
    } catch(err) {
            console.log('The native context does not exist yet');
    }
}
Run Code Online (Sandbox Code Playgroud)

迅速

import WebKit
class ViewController: UIViewController, WKScriptMessageHandler {

    @IBOutlet var containerView: UIView? = nil

    var webView: WKWebView?

    override func loadView() {
        super.loadView()

        let contentController = WKUserContentController()
        contentController.addScriptMessageHandler(self, name: "callbackHandler")
        let config = WKWebViewConfiguration()
        config.userContentController = contentController

        self.webView = WKWebView( frame: self.containerView!.bounds, configuration: config)
        self.view = self.webView

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //I use the file html in local
        let path = NSBundle.mainBundle().pathForResource("index", ofType: "html") 
        let url = NSURL(fileURLWithPath: path!)
        let req = NSURLRequest(URL: url)
        self.webView!.loadRequest(req)

    }

    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {// edit: changed fun to func
        if (message.name == "callbackHandler"){
            print("\(message.body)")
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

对于一个UIWebView:源在这里

HTML中的JavaScript

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>
        (function(){
            $(window).load(function(){

               $('.clickMe').on('click', function(){
                   window.location = "foobar://fizz?Hello_from_javaScript";
               });
            });
         })(jQuery);
    </script>
Run Code Online (Sandbox Code Playgroud)

迅速

import UIKit
class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var Web: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

    let path = NSBundle.mainBundle().pathForResource("index", ofType: "html")
        let url = NSURL(fileURLWithPath: path!)
        let req = NSURLRequest(URL: url)
        Web.delegate = self
        Web.loadRequest(req)
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if request.URL?.query != nil {
            print("\(request.URL!.query!)")
        }
        return true
    }

}
Run Code Online (Sandbox Code Playgroud)


pau*_*lvs 5

这是一个快速示例:

  1. foobar在 Xcode 中注册一个 URL Scheme
  2. 在您的 Web 视图中处理此 URL Scheme

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if request.URL?.query?.containsString("show_activity_indicator=true") {
            myActivityIndicator.startAnimating()
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 最后,从你的 JavaScript 调用它

    // Show your activity indicator from JavaScript.
    window.location = "foobar://fizz?show_activity_indicator=true"
    
    Run Code Online (Sandbox Code Playgroud)

注意:有关iOS 中 Web 视图通信的更多信息,请在此处查看我的问题