[iOS Development]wkwebview loading JS

Source: Internet
Author: User

Recently project to use WebView load JS file, very colleague said Wkwebview than UIWebView more useful, so I try today, Baidu, wrote a demo.

First look at the code I wrote, and then see the difference between Wkwebview and UIWebView:

  First, follow these two protocols wknavigationdelegate,wkscriptmessagehandler.

  Next, get the JS text.

JS Interaction

-(void) Getjs {

NSString * js = @ "Window.webkit.messageHandlers.observe.postMessage (document.body.innerText);";// Note that the observe field here is written by itself, not a fixed notation, referring to line 6th

Wkuserscript *wkuserscript = [[Wkuserscript alloc]initwithsource:js Injectiontime: Wkuserscriptinjectiontimeatdocumentend formainframeonly:yes];//here atdocumentend field refers to the content of the Web page after loading and then inserting JS script, you can also choose Atdocumentstart, insert the script when the document element is just created to see the specific requirements

Wkwebviewconfiguration *config = [[Wkwebviewconfiguration alloc]init];

[Config.usercontentcontroller Adduserscript:wkuserscript];

[Config.usercontentcontroller addscriptmessagehandler:self name:@ "observe"];

Config.userContentController.addScriptMessageHandler (Self, Name: "observe")//corresponding to the observe field in the first line of JS script

Initialize Wkwebview

Self.webview = [[Wkwebview alloc]initwithframe:cgrectmake (0, 0, Self.view.frame.size.width, self.view.frame.size.height) Configuration:config];

[Self.view Addsubview:_webview];

Self.webView.navigationDelegate = self;

Loading Web pages

[Self.webview loadrequest:[nsurlrequest requestwithurl:[nsurl urlwithstring:@ "http://www.jianshu.com"]];

_webview.loadrequest (Nsurlrequest (Url:nsurl (string: "http://www.jianshu.com")!))

}

  Then, implement the methods of both protocols.

Common proxy methods

-(void) Usercontentcontroller: (Wkusercontentcontroller *) Usercontentcontroller didreceivescriptmessage: ( Wkscriptmessage *) message{

NSString *str = message.body;//Because we crawl to the text, here the Message.body cast to NSString, if you get the other information through JS, on-demand conversion

NSLog (@ "%@", str);

}

#pragma mark-Ready to load the page

-(void) WebView: (Wkwebview *) WebView didstartprovisionalnavigation: (wknavigation *) Navigation {

}

#pragma mark-has started loading the page, you can add a transition animation to the view in this step

-(void) WebView: (Wkwebview *) WebView didcommitnavigation: (wknavigation *) Navigation {

}

#pragma mark-//Load page failed

-(void) WebView: (Wkwebview *) WebView didfailnavigation: (wknavigation *) navigation Witherror: (Nserror *) Error {

}

-(void) WebView: (Wkwebview *) WebView didfailprovisionalnavigation: (wknavigation *) navigation Witherror: (Nserror *) Error {

}

Finally, you can run.

  Now we can talk about the differences between the two controls.

Wkwebview is faster (memory may only be UIWebView 1/3~1/4), there is no cache , and a more granular way to split uiwebviewdelegate.
To learn more about Wkwebview's features, you can do it yourself, and you can simply think of it as a lightweight uiwebview.

From now on, the APP is only compatible with iOS 8 and iOS 92 versions (if your product is less demanding on coverage). Wkwebview is the content in the WebKit after iOS 8, so before we were compatible with iOS 7 and iOS 8, we could say that UIWebView and Wkwebview did too much trouble, and now there's no reason to reject something new.
  

In Wkwebview, Uiwebviewdelegate and UIWebView are heavily composed of 14 classes and 3 protocols, and some wkwebview versions of the methods commonly used in UIWebView are given below.

Preparing to load the page
UIWebViewDelegate - webView:shouldStartLoadWithRequest:navigationType
WKNavigationDelegate - webView:didStartProvisionalNavigation:

Started loading the page, you can add a transition animation to the view in this step

UIWebViewDelegate - webViewDidStartLoad:

WKNavigationDelegate - webView:didCommitNavigation:

//page has been fully loaded, you can remove the transition animation in this step
UIWebViewDelegate - webViewDidFinishLoad:
WKNavigationDelegate - webView:didFinishNavigation:

//Load page failed
UIWebViewDelegate - webView:didFailLoadWithError:
WKNavigationDelegate - webView:didFailNavigation:withError:
WKNavigationDelegate - webView:didFailProvisionalNavigation:withError:

the above methods exist in Uiwebviewdelegate and Wknavigationdelegate respectively.
If you have used only a few of the above listed uiwebviewdelegate, then simply change the method name, let your viewcontroller inherit wknavigationdelegate, continue to use it. For more content, you can use the CMD key + mouse left click "Wknavigationdelegate" to view through Xcode.
Note that you webview.delegate = self need to overwrite the webview.navigationDelegate = self .

[iOS Development]wkwebview loading JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.