I want to call a JavaScript function like:
- (void)alertMe:(NSString *)msg {
[[[UIAlertView alloc] initWithTitle:@"Alert" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
}
and
function alertMe(msg) {
alert(msg);
}
How can I call it using XCode if the HTML file is loaded on a UIWebView in XCode
Use the delegate method UIWebView
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
implement query string for your javascript function
You can use EasyJSWebView to easily implement calling Native Objective-C
method from JavaScript
. The more convenient way is to implement a class that holds all your methods that your JS
will call and instantiate that class with your UIWebView Control Object subclass with EasyJSWebView as an argument.
For example: I created a class JSInterface
to hold all my native Obj-C methods
I have a custom method
- (void)initializeJSInterfaceForWebView:(EasyJSWebView *)webView {
self.jsInterface.appDelegate = appDelegate;
self.jsInterface.webView.delegate = self;
[webView addJavascriptInterfaces:self.jsInterface WithName:@"nativeInterface"];
}
that will initialized EasyJSWebView
.
I instantiate
self.jsInterface = [JSInterface initWithView:self];
[self initializeJSInterfaceForWebView:self.webView];
For instance, we have a native Objective-C
method:
- (void) printLog:(NSString *)msg {
NSLog(@"%@", msg);
}
To call on the native method from JavaScript
using the nativeInterface
object name as follows:
nativeInterface.printLog("This is only a test.");
You may want to implement query string for your JavaScript function ei:
function getQueryString(){
var mySearch = window.location.search.substr(1).split("&");
if (mySearch!="")
{
for(var x=0;x<mySearch.length;x++) {
// loop to all your query string here
}
}
}//end function
Or you may also want to use the method
[webView stringByEvaluatingJavaScriptFromString:(NSString*)]
where you may call you local javascript like:
[webView stringByEvaluatingJavaScriptFromString:@"javascript:myJSFunction()"];
Bu this method can only be called within the webViewDidFinishLoad:(UIWebView *)webView
and/or when called within webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
method the return
must be NO
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.