Swift中的UIWebView和JavaScriptInterface

时间:2016-05-20 22:11:53

标签: ios swift uiwebview

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

Android中的示例:

webView.addJavascriptInterface(new WebAppInterface(this), "Android");

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

func webViewDidStartLoad(webView: UIWebView)

myActivityIndicator.startAnimating()

我该怎么办?

2 个答案:

答案 0 :(得分:12)

对于WKWebView:来源here

的JavaScript

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

夫特

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)")
        }
    }

}

对于UIWebView:来源here

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>

夫特

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
    }

}

答案 1 :(得分:4)

这是一个简单的例子:

  1. 在Xcode
  2. 中注册foobar等URL方案
  3. 在网络视图中处理此网址

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if request.URL?.query?.containsString("show_activity_indicator=true") {
            myActivityIndicator.startAnimating()
        }
    }
    
  4. 最后,从您的JavaScript中调用它

    // Show your activity indicator from JavaScript.
    window.location = "foobar://fizz?show_activity_indicator=true"
    
  5. 注意:有关iOS中的网络视图通信的详细信息,请参阅my question here