Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

ios - UIWebView and JavaScriptInterface in Swift

How can I to create the JavascriptInterface channel from my web site to my UIWebView?

Example in Android:

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

And from this JavascriptInterface I would like to draw the methods, as for example:

func webViewDidStartLoad(webView: UIWebView)

or

myActivityIndicator.startAnimating()

How can I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For WKWebView: source here

JavaScript

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

Swift

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

}

For UIWebView: source here

JavaScript in HTML

        <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>

Swift

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
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...