A lot of OBJC and JS Interactive articles are more suitable for Mac development, iOS WebView or something different, reference: Http://blog.sina.com.cn/s/blog_ 693de6100102vhuh.html This article provides a good solution to the UIWebView within the JS and OBJC interaction ideas.naturally, from OC to JS, you can use stringbyevaluatingjavascriptfromstring: to achieve. from JS to OC, using a more ingenious design,UIWebView browser intercepts URL requests, customizing URLs in a way that intercepts interactions please.--------------------------------------------------------------------------------------------------
UIWebView is the control that renders the mesh in the iOS SDK, and when the page is displayed, we can hack the page and display what we want to display. There is a need to use JavaScript knowledge, and the way UIWebView interacts with JavaScript is stringbyevaluatingjavascriptfromstring:
With this approach we can invoke JavaScript via OBJC and inject JavaScript.
First, let's take a look at how to invoke JavaScript:
- [WebView stringbyevaluatingjavascriptfromstring:@ "myFunction ();"];
Here MyFunction () is our JavaScript method.
To see what to inject into JavaScript, let's start by writing a JavaScript that needs to be injected:
- function Showalert () {
- Alert (' In Show alert ');
- }
Save As Test.js, and then drag to the resource group under Xcode. Then use the code to inject this JS (as in the Viewdidload method) when initializing.
- NSString *filepath = [[NSBundle mainbundle] pathforresource:@ "test" oftype:@ "JS"];
- NSString *jsstring = [[NSString alloc] initwithcontentsoffile:filepath];
- [WebView stringbyevaluatingjavascriptfromstring:jsstring];
This will inject the above JS, then we can call the JS method at any time, how to invoke, the above is introduced.
Then we can use JS to invoke the OBJC method. Of course, the principle is to use UIWebView Redirect request, pass some commands to our UIWebView, in UIWebView delegate method to receive these commands, and according to the command to execute the corresponding OBJC method. This is equivalent to calling the ObjC method in JavaScript. That's a little bit abstract, just look at the code.
First we write a JavaScript method as follows:
[JavaScript]
- function SendCommand (cmd,param) {
- var url= "TestApp:" +cmd+ ":" +param;
- document.location = URL;
- }
- function Clicklink () {
- SendCommand ("alert", "How are You?") ");
- }
Then call this JS method in your HTML, such as:
[JavaScript]
- "Button" value= "click me!" onclick= "Clicklink ()"/>
Finally we intercept this redirect request in Uiwebvew:
- #pragma mark--
- #pragma Mark Uiwebviewdelegate
- -(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype {
- NSString *requeststring = [[Request URL] absolutestring];
- Nsarray *components = [requeststring componentsseparatedbystring:@ ":"];
- if ([Components Count] > 1 && [(NSString *) [objectatindex:0] isequaltostring:@ "TestApp"]) {
- if ([(NSString *) [Components objectatindex:1] isequaltostring:@ "alert"])
- {
- Uialertview *alert = [[Uialertview alloc]
- initwithtitle:@ "Alert from Cocoa Touch" Message:[components Objectatindex:2]
- Delegate:self Cancelbuttontitle:nil
- otherbuttontitles:@ "OK", nil];
- [Alert show];
- }
- return NO;
- }
- return YES;
- }
But there is an open source project that you can look at, which allows JavaScript to invoke the Objective_c method. Call
Jsbridge-to-cocoa http://code.google.com/p/jsbridge-to-cocoa/
There are two other related projects
Webviewjavascriptbridge and Gajavascript are worth studying slowly.
Other
Inserting JS Code
The above function we can encapsulate into a JS function, the function is inserted into the page execution, the code is as follows:
if ([title Compare: @ "Google"]==nsorderedsame) {
[WebView stringbyevaluatingjavascriptfromstring:@ "var script = document_createelement_x_x (' script ');"
"Script.type = ' text/javascript ';"
"Script.text =" function myFunction () {"
"var field = document.getelementsbyname (' q ') [0];"
"Field.value= ' Zhu Qilin ';"
"Document.forms[0].submit ();"
"}";"
"Document.getelementsbytagname_r (' head ') [0].a (script);"];
[WebView stringbyevaluatingjavascriptfromstring:@ "myFunction ();"];
}
Look at the code above:
A, first through the JS create a script tag, type ' Text/javascript '.
b, and then insert a string in this tag, this string is a function: MyFunction, this function to implement the Google auto-search keyword function.
c, and then use Stringbyevaluatingjavascriptfromstring to execute the MyFunction function.
1. General invocation
The local data, encapsulated, directly as the return value of JS. Such as: Access to software Appcode
Get Appcode
Nsarray *_plist_paths=nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes);
NSString *_plist_paths_path=[_plist_paths objectatindex:0];
Nsarray *_plist_array= [_plist_paths_path componentsseparatedbystring:@ "/"];
NSString *_appcode=[[nsstring Alloc]init];
For (NSString *item in _plist_array) {
if ([item length]==36) {
_appcode=item;
Break
}
}
NSLog (@ "Current appcode:%@", _appcode);
Inject into JS
Nsmutablestring *_getapkcode=[[nsmutablestring Alloc]init];
[_getapkcode appendformat:@ "function _getapkcode () {"];
[_getapkcode appendformat:@ "return '%@ ';", _appcode];
[_getapkcode appendstring:@ "}"];
[Self.webview Stringbyevaluatingjavascriptfromstring:_getapkcode];
[_getapkcode release];
2. Need to interact with the platform to invoke
Ideas:
1. Manufacture of requests with certain meanings such as: (location.href= "Download");
2. In method:-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype, intercept:
testmall:http://192.168.1.20:8083 Local test page address
NSString *pre_download=[nsstring stringwithformat:@ "% @downLoad", Testmall];
if ([url hasprefix:pre_download])
{
Download code ....
}
3. Precautions
a. There is an IFRAME nested page, JS injection
page injection JS is injected into the HTML of the browser, for the internal nested IFRAME Framework page , you cannot call to JS. This is the equivalent of invoking the parent page JS.
b. There is an interaction processing method. Recommended use, the iphone is only responsible for providing JS interface, do not call the HTML internal or other JS interface
  
example:
html
function adddownload ()
{
url= ' www.XXX.XXX.zip ';
download (URL);//Invoke the JS interface provided by iphone
adddownloadtask_ret ();//Get the download result of the iphone download interface, here is a local delay method
//get download results from iphone download interface
Function Adddownloadtask_ret ()
{
var obj= Getdownloadtaskresult ();//The interface provided here for the iphone is responsible for returning the results of the current download execution if ('!=obj| | Undefined!=obj)
{
//Invoke some of the local post-processing methods.
}
Else
{
SetTimeout ("Adddownloadtask_ret2 ();", +);
}
} -------------------------------------------------
UIWebView and JavaScript (JS) callback Interaction-Standby