Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does UIWebView on iOS have methods to add interface to DOM?

For android there is a method named addJavascriptInterface() which imports an Android JAVA object to Javascript context. Is there any equivalent of it on iOS? I have gone through some of the similar questions :
androids-addjavascriptinterface-equivalent-in-ios
calling-objective-c-function-from-javascript-in-ios-applications
But could not find a proper solution to my question .

function initiateAddCall(){
        var locus = reader.getPlace().getLocus();
        RoomHelper.postReaderLocus(JSON.stringify(locus));
}

RoomHelper is the javascript handler which am using . Is there any way i can implement this (Register a javascript handler/interface in UIWebView iOS) in UIWebView iOS .

like image 562
TomCoder09 Avatar asked Oct 24 '15 12:10

TomCoder09


2 Answers

I just used EasyJSWebView and worked pretty well. There are others solutions like WebViewJavascriptBridge but EasyJSWebView was easier to use.

RoomHelper *roomHelper = [RoomHelper new];
[self.myWebView addJavascriptInterfaces:interface WithName:@"RoomHelper"];
[self.myWebView injectJS:webView];

in javascript you call:

RoomHelper.test()

and in RoomHelper you implement a method called test

RoomHelper.h :

@interface RoomHelper : NSObject

- (void) test;

@end
like image 173
Ryniere Silva Avatar answered Oct 21 '22 00:10

Ryniere Silva


Had to use this for a native app project where i was using D3.JS to show the graphs. Used the below code to call the JS function

    NSString *jsString = [NSString stringWithFormat:@"showLegendGraphsFromDevice('%@',%d)",sectionName, position];
    [_webView stringByEvaluatingJavaScriptFromString:jsString];

Here

function showLegendGraphsFromDevice(name, position) 

is the JS function

Key here is creating the correct JS string with the needed quotes.

like image 25
premith Avatar answered Oct 21 '22 02:10

premith