WebView for front end engineers

Tencent imweb team 2021-02-23 04:02:50
webview end engineers


| Introduction Today, , Doing mobile H5 When developing , There is no shortage of Native Interact with each other . And in the Native in ,H5 The loading container of is WebView, Its core is the use of WebView Control to load url.

WebView The concept of

WebView Used to display the web page view Components , This component is the basis for you to run your own browser or display online content in your thread . Use Webkit Rendering engine to show , And support forward and backward based on browsing history , Zoom in and out , And more .

Simply speaking WebView It's a high-performance phone built in Webkit Kernel browser , stay SDK A component encapsulated in . However, the address bar and navigation bar are not provided , It's just a web interface .

The above is the description of a client developer , And from the perspective of a front-end Developer , The feeling after use is :

WebView It can be simply understood as iframe . Native app And WebView The interaction between pages can be simply seen as between pages and within pages iframe Page interaction . It's like the page and the iframe Share one Window equally , Primitive and WebView It also shares a native approach .

Now that we use WebView To carry H5, Then it is necessary to communicate with Native There's an interaction between ,WebView The page that it carries , adopt JS And Native communicate , We're going to send this message to ” bridge “ by JSBridge. If you have participated in the development of wechat's built-in browser H5 Development , You'll find something that happens all the time , be called WeixinJSBridge.

JSBridge

JSBridge simply , Mainly to JavaScript Provide calls Native Functional interface , Let the... In mixed development 『 The front end 』 Easy to use address location 、 Cameras, even payments, etc Native function .

Since it is 『 simply 』, that JSBridge It's certainly not just for 『 call Native function 』 So simple and broad . actually ,JSBridge It's like in the name 『Bridge』 It means the same thing , yes Native He Fei Native The bridge between , At its core structure Native He Fei Native A channel for message communication between two computers , And it's Two way communication channel . So-called Two way communication channel :

  • JS towards Native Send a message : Call related functions 、 notice Native At present JS And so on .

  • Native towards JS Send a message : Trace back the result of the call 、 Message push 、 notice JS At present Native And so on .

JavaScript It's running in a separate JS Context in ( for example ,WebView Of Webkit engine 、JSCore). Because of these Context Natural isolation from the original operating environment , We can relate this to RPC(Remote Procedure Call, Remote procedure call ) Communication analogy , take Native And JavaScript Call each other as once RPC call . So we can follow the usual RPC Design and implement in different ways .

stay JSBridge In the design of , Think of the front end as RPC The client of , hold Native End as RPC Server side of , thus JSBridge The main logic to be implemented comes out : Communication call (Native And JS signal communication and Handle resolution call .( If you're a front end , And not familiar with RPC Words , You can also compare this process to JSONP The process of .)

Through the above analysis , It is clear that JSBridge Main functions and responsibilities , Next , Let's analyze it Android WebView and iOS WebView To realize Native And JS The principle of communication .

Android WebView

Android 4.4 front :Android WebView In low version & Higher versions use different Webkit Version of the kernel ( Because of that ,H5 A lot of new features of , stay Android Version less than 4.4 On our Android , Don't support ) Android 4.4 after : Originally based on Webkit Of WebView Start based on Chromium kernel , This change has greatly improved WebView The performance of the component and its impact on HTML5, CSS3, JavaScript Support for . But its API But there's no big change , While compatible with the lower version, only a few new API, It doesn't take you to make a big change .

stay Android WebView, To achieve JS call Java, Yes 3 Methods :

  • JavascriptInterface
  • WebViewClient.shouldOverrideUrlLoading()
  • WebChromeClient.onXXX()

1、 JavascriptInterface

This is a Android Provided JS And Native The official solution for communications .

First Native The end needs to implement such a class , to JavaScript call .

public class WebAppInterface {
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
 Copy code 

And then put this WebAppInterface class , Through the following code , Add to WebView Of JavaScriptInterface in .

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
// there Android Will be treated as a variable , Injected into the page window in .
 Copy code 

Then you can go to JS Call in Native 了 .

function showAndroidToast(toast) {
Android.showToast(toast);
}
 Copy code 

2、WebViewClient.shouldOverrideUrlLoading()

The purpose of this method is to intercept all WebView Of URL Scheme .

URL Scheme It's something like URL Link to , It's for convenience app Call each other directly , Form and common URL The approximate , The main difference is protocol and host It's usually custom .

Intercept URL Scheme The main process of :Web In some way ( for example iframe.src/location.href) send out URL Scheme request , after Native Intercept the request and follow URL Scheme( Including the parameters ) Carry out relevant operations .

A page can be constructed in a special format URL Scheme Trigger ,shouldOverrideUrlLoading Intercept URL Then judge the format , then Native You can execute your own logic .

public class CustomWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(
WebView view,
String url
) {
if (isJsBridgeUrl(url)) {
// JSbridge Processing logic 
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
}
 Copy code 

3、WebChromeClient.onXXX()

By modifying the original browser's window Some methods , Then intercept the parameters of the fixed rule , And then distribute it to Java The corresponding way to deal with

  • alert, Can be WebView Of WebChromeClient.onJsAlert() monitor
  • confirm, Can be WebView Of WebChromeClient.onJsConfirm() monitor
  • console.log, Can be WebView Of WebChromeClient.onConsoleMessage() monitor
  • prompt, Can be WebView Of WebChromeClient.onJsPrompt() monitor

prompt Give a simple example ,Web Page by calling prompt() Method , Android clients listen through WebChromeClient.onJsPrompt() event , Intercept incoming parameters , If the parameters meet certain protocol specifications , So parse the parameters , Throw it to the following Java To deal with .

window.prompt(message, value);
 Copy code 

WebChromeClient.onJsPrompt() Will be called back .onJsPrompt() Methodical message The value of the parameter is exactly JS Methods window.prompt() Of message Value .

public class CustomWebChromeClient extends WebChromeClient {
@Override
public boolean onJsPrompt(
WebView view,
String url,
String message,
String defaultValue,
JsPromptResult result
) {
// Handle JS Call logic of 
result.confirm();
return true;
}
}
 Copy code 

Java call JavaScript

Android, stay Kitkat(4.4) Only use loadUrl a section JavaScript Code .

webView.loadUrl("javascript:" + javaScriptString);
 Copy code 

and Kitkat Later versions , It can also be used. evaluateJavascript Method realization :

webView.evaluateJavascript(javaScriptString, new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
// native Code 
}
});
 Copy code 

IOS WebView

In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView. Additionally, consider setting the WKPreferences property javaScriptEnabled to NO if you render files that are not supposed to run JavaScript.

stay IOS8 Before , Apple Mobile WebView The use of UIWebView,UIWebView There have been some problems for a long time :

  • Slow loading speed
  • There is a memory leak
  • A lot of memory , Memory optimization is difficult
  • If the memory is occupied too much, it may be occupied by the system kill fall

stay WWDC 2014 At the conference ,IOS8 Launched WKWebView,WKWebView It's modern Webkit API stay iOS 8 and OS X Yosemite The core part of the application . It replaces UIKit Medium UIWebView and AppKit Medium WebView, Provides a unified cross dual platform API. Have 60fps Scroll refresh rate 、 Built in gestures 、 efficient app and web Information exchange channel 、 and Safari same JavaScript engine .

JavaScript ︎ Swift Dialogue mechanism

Use user scripts to inject JavaScript

WKUserScript Allow injection into the page before or after body loading . This powerful feature allows you to manipulate the content of a web page in a secure and unique way .

A simple example is as follows , The user script that the user changes the background is inserted into the web page :

let source = "document.body.style.background = #777";
// Inject script Execute after the document is loaded 
let userScript = WKUserScript()
let userScript = WKUserScript(source: source, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)
let userContentController = WKUserContentController()
userContentController.addUserScript(userScript)
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
self.webView =WKWebView(frame: self.view.bounds, configuration: configuration)
 Copy code 

Objects can be represented as JavaScript Source form initialization , During initialization, you can also pass in whether to inject before loading or at the end of loading , And whether scripts affect this layout or just the main layout . So user scripts are added to WKUserContentController in , And take WKWebViewConfiguration Attribute passed to WKWebView In the initialization process .

This example can be simply extended to a more advanced page modification method , For example, removing advertisements 、 Hide comments, etc .

Message Handlers

Use the following code , Can follow Native communicate

window.webkit.messageHandlers.{NAME}.postMessage()
 Copy code 

Handler Of name Can pass WKScriptMessageHandler In the agreement addScriptMessageHandler() Interface function settings :

class NotificationScriptMessageHandler: NSObject, WKScriptMessageHandler {
func userContentController(
userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage!
) {
println(message.body)
}
}
let userContentController = WKUserContentController()
let handler = NotificationScriptMessageHandler()
userContentController.addScriptMessageHandler(handler, name: "notification")
 Copy code 

So when the notice enters app When , For example, create a new object in the page , That's how the information can be delivered :

window.webkit.messageHandlers.notification.postMessage({body: ' Send to Native'});
 Copy code 

Add user scripts to web Monitor events and use Message Handler Send the message back to app.

summary

The principle of communication is JSBridge The core of implementation , There are many ways to do this , But everything is the same . here , The recommended implementation is as follows :

  • JavaScript call Native Recommended Inject API The way .( iOS6 Ignore ,Android 4.2 The following uses WebViewClient Of onJsPrompt The way .)

  • Native call JavaScript Then directly execute the spliced JavaScript The code can be .

For other ways , Such as React Native、 Wechat applet All the communication modes are similar to those described above , And optimize according to the actual situation .

With React Native Of iOS End example :JavaScript Running on the JSCore in , In fact, it can be the same way as above , Using injection API To achieve JavaScript call Native function . however React Native It's not designed to JavaScript Call directly Object-C, It is In order to Native The event response mechanism is consistent in development , Designed to Need to be in Object-C Detuning JavaScript The call is triggered by the return value . The principle is basically the same , It's just a different way of doing it .

版权声明
本文为[Tencent imweb team]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210223024103595m.html

  1. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  2. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  3. Vue determines whether the El form in the elementui is updated or changed. If it changes, it will prompt whether to save it. If it does not change, it will leave directly
  4. Algorithm problem: sum of two numbers -- JavaScript and Java implementation
  5. High performance nginx HTTPS tuning
  6. JQuery advanced
  7. day 30 jQuery
  8. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  9. TCP/IP 开胃菜 之 HTTP
  10. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  11. JavaScript data type
  12. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  13. Solve Ajax cross domain problem [5 solutions]
  14. HTTP of TCP / IP appetizer
  15. Optimization of pod creation efficiency in serverless scenario
  16. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%
  17. First knowledge of HTTP / 1.1
  18. First knowledge of HTTP / 1.1
  19. Webpack learning notes series 05 devserver
  20. Webpack learning notes series 04 - resource processing optimization
  21. How to build a high performance front end intelligent reasoning engine
  22. How to become a professional front end engineer in 2021?
  23. How to transform single / micro service application into serverless application
  24. How to transform single / micro service application into serverless application
  25. How to transform single / micro service application into serverless application
  26. How to connect the ground gas to the micro front end?
  27. How to connect the ground gas to the micro front end?
  28. How to connect the ground gas to the micro front end?
  29. Vue server rendering principle analysis and introduction
  30. Realize the correct loading of text message
  31. Building my own project scaffolding with yeoman
  32. JavaScript advanced prototype and prototype chain
  33. React background management front end system (based on open source framework development) start
  34. JS practical skills breakpoint debugging
  35. I'd like to share with you 20 super easy-to-use Chrome extension plug-ins
  36. Get page element location
  37. Use the powerful API of modern browser to record any interface in the browser and realize export, save and management
  38. Delayed code execution in flutter
  39. Reconfiguration experience of KOA middleware system
  40. Add comments to your blog
  41. Svg editor -- new path
  42. Detailed explanation of debounce and throttle of JavaScript function
  43. Anti shake and throttling and corresponding react hooks package
  44. C2m: the first CSDN article moved to MOOC script 5000 words, detailed painstaking development process, there are renderings and source code at the end of the article
  45. Front end, school recruitment, Taobao, guide
  46. [vue2 & G6] get started quickly
  47. Canvas from the beginning to the pig
  48. Take five minutes to standardize the code comments?
  49. Some thoughts on sass
  50. what?! You haven't filled in the award information yet
  51. How to get the interface + tsdoc needed by TS through swagger
  52. Binary tree
  53. Canvas drawing method in Web screenshot
  54. Front end docker image volume optimization (node + nginx / node + multi-stage construction)
  55. Become a big influence of technology? Coding pages quickly build personal blog
  56. Object and array deconstruction, spread operator, rest operator
  57. Analysis of Axios source code
  58. Two ways to delete useless code in project (Practical)
  59. Edit your picture with canvas
  60. Today's chat: 2-4 years to walk out of the resignation dilemma and comfort zone