Call Swift Function with JavaScript Using Uiwebview

Call swift function with javascript using UIWebview

Implement listenInSwift like this:

function listenInSwift() {
window.location = 'yoururlscheme://somehost?greeting=hello'
}

Then listen for this URL with this code in your UIWebViewDelegate class:

func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType navigationType: UIWebViewNavigationType) -> Bool {
if request.URL.scheme == 'yoururlscheme' {
print('Hello JavaScript...')
}
}

Don't forget to register your URL Scheme (in this case 'yoururlscheme') in Xcode.

To load a local file in the web view, try this:

let baseURL = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath);
let relativePath = "www/\(file)"
let fileURL = NSURL(string: relativePath, relativeToURL: baseURL);
let URLRequest = NSURLRequest(URL: fileURL!);
webView.loadRequest(URLRequest)

Javascript call to Swift from UIWebView

You must a custom URL Scheme such as myawesomeapp and intercept requests to it using:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool

Fire a call to native code using window.location=myawesomeapp://hello=world, and get the query params you pass from request.URL.query in the native code.

For more information, see my question about UIWebViews here: JavaScript synchronous native communication to WKWebView

Calling Javascript using UIWebView

Simple: You try to execute the JS function from Objective-C before the page even has been loaded.

Implement the UIWebView's delegate method webViewDidFinishLoad: in your UIViewController and in there you call [graphView stringByEvaluatingJavaScriptFromString:@"methodName()"]; to make sure the function gets called after the page has been loaded.

Call JavaScript function from native code in WKWebView

(I filed a Radar for this shortly after asking the question here.)

A new method was just added a few days ago (thanks jcesarmobile for pointing it out):

Add -[WKWebView evaluateJavaScript:completionHandler:]
http://trac.webkit.org/changeset/169765

The method is available in iOS 8 beta 3 and up. Here's the new method signature:

/* @abstract Evaluates the given JavaScript string. 
@param javaScriptString The JavaScript string to evaluate.
@param completionHandler A block to invoke when script evaluation completes
or fails.
@discussion The completionHandler is passed the result of the script evaluation
or an error.
*/
- (void)evaluateJavaScript:(NSString *)javaScriptString
completionHandler:(void (^)(id, NSError *))completionHandler;

Docs are available here: https://developer.apple.com/documentation/webkit/wkwebview/1415017-evaluatejavascript.

UIWebView and JavaScriptInterface in Swift

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
}

}


Related Topics



Leave a reply



Submit