1. First import the Javascriptcore.framework framework
2. Create a webview, set up a proxy, request a phone-side Baidu
#import "ViewController.h"#import<JavaScriptCore/JavaScriptCore.h>#defineScreen_width [UIScreen mainscreen].bounds.size.width#definescreen_height [UIScreen mainscreen].bounds.size.height@interfaceViewcontroller () <UIWebViewDelegate>@property (strong,nonatomic) UIWebView*WebView; @property (assign,nonatomic) BOOL isfirstloadweb;@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; Self.webview=[[UIWebView alloc]initwithframe:self.view.bounds]; Self.webView.scalesPageToFit=YES; Self.webView.backgroundColor=[Uicolor Clearcolor]; Self.webview.Delegate=Self ; [Self.view AddSubview:self.webView]; Nsurl*url = [Nsurl urlwithstring:@"http://m.baidu.com"]; Nsurlrequest*request =[[Nsurlrequest Alloc]initwithurl:url]; [Self.webview loadrequest:request];}
3. Through proxy method, call the custom JS script inside
-(void) Webviewdidfinishload: (UIWebView *) webview{//The program will always call this method, so that if the first load after using our custom JS, and then no longer call JS, otherwise there will be page jitter phenomenon if(!_isfirstloadweb) {_isfirstloadweb=YES; //gets the URL of the current pageNSString *url = [WebView stringbyevaluatingjavascriptfromstring:@"Document.location.href"]; //gets the title of the pageNSString *title = [WebView stringbyevaluatingjavascriptfromstring:@"Document.title"]; NSLog (@"%@----%@", Url,title); //Add a custom JavaScript to WebView[WebView stringbyevaluatingjavascriptfromstring:@"var script = document.createelement (' script ');" "script.type = ' text/javascript ';" "script.text = \ "Function myfuncation () {" "var field = document.getelementsbyname (' word ') [0];" "field.value = ' Charciensen's blog Park ';" "document.forms[0].submit ();" "}\";" "document.getelementsbytagname (' head ') [0].appendchild (script);"]; //start calling custom JavaScript[WebView stringbyevaluatingjavascriptfromstring:@"myfuncation ();"]; }Else{ return; }}@end
The demo is as follows:
----£ º24.670 OC call js[7568:356964 ] https://m.baidu.com/----Baidu a bit
IOS: Invoking JS script in OC: Example one