<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lorenzo Pichilli on Medium]]></title>
        <description><![CDATA[Stories by Lorenzo Pichilli on Medium]]></description>
        <link>https://medium.com/@pichillilorenzo?source=rss-11e6aac5f656------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c5CI9wg1E2VfTJZxDjgueA@2x.jpeg</url>
            <title>Stories by Lorenzo Pichilli on Medium</title>
            <link>https://medium.com/@pichillilorenzo?source=rss-11e6aac5f656------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:56:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pichillilorenzo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Convert a PWA Into a Flutter App Using WebViews]]></title>
            <link>https://medium.com/better-programming/convert-a-pwa-into-a-flutter-app-using-webviews-387060548a37?source=rss-11e6aac5f656------2</link>
            <guid isPermaLink="false">https://medium.com/p/387060548a37</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Lorenzo Pichilli]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 16:16:49 GMT</pubDate>
            <atom:updated>2022-12-06T16:16:49.730Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to convert a PWA into a Flutter app using Flutter’s InAppWebView 6 plugin</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R2yKmdvL8E2l8u2i" /><figcaption>Photo by <a href="https://unsplash.com/@olafval?utm_source=medium&amp;utm_medium=referral">Olaf Val</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we are going to convert a <a href="https://web.dev/progressive-web-apps/">PWA (Progressive Web App)</a> into a Flutter Mobile App for Android and iOS using the latest version 6 of the <a href="https://github.com/pichillilorenzo/flutter_inappwebview">flutter_inappwebview</a> plugin.</p><h3>What are Progressive Web Apps?</h3><p>Progressive Web App is a term that refers to web applications that are developed and loaded like regular web pages but which behave similarly to native applications when used on a mobile device.</p><p>They are built and enhanced with modern APIs to deliver enhanced capabilities, reliability, and installability while reaching anyone, anywhere, on any device with a single codebase. Progressive Web Applications leverage this dynamism of the new web along with technologies like service workers and manifest to offer a native app-like user experience that works even when the user is offline.</p><p>Developers can publish the web application online, ensure that it meets baseline installation requirements, and users can add the application to their home screen. Publishing the app to digital distribution systems like Apple App Store or Google Play is optional.</p><h3>What are Hybrid Apps?</h3><p>Hybrid apps are applications that combine the features of both native apps and web apps. They run inside a container, in this case, a WebView.</p><p>They are available via app stores, can access native APIs and the hardware components of your phone, and are installed on your device, just like a native app.</p><p>I won’t explain the pros and cons between PWAs, Native Apps, and Hybrid Apps because it’s beyond the scope of this article. You can already search for it on the web.</p><h3>How To Convert a PWA to a Flutter App</h3><p>As a PWA example, we will use <a href="https://mdn.github.io/pwa-examples/js13kpwa/">https://mdn.github.io/pwa-examples/js13kpwa/</a> (GitHub repo: <a href="https://github.com/mdn/pwa-examples/blob/master/js13kpwa">js13kpwa</a>), which is a fully functional PWA with offline support.</p><p><a href="https://github.com/mdn/pwa-examples/blob/master/js13kpwa">js13kpwa</a> is a list of A-Frame entries submitted to the js13kGames 2017 competition, used as an example for the MDN articles about Progressive Web Apps. The js13kPWA has the app shell structure, works offline with the service worker, is installable thanks to the manifest file and Add to Homescreen feature, and is re-engageable by using notifications and push.</p><p>Also, for this use case, we will add a simple two-way communication between JavaScript and Flutter/Dart.</p><h4>Service workers</h4><p>Service workers are a fundamental part of a PWA. They enable fast loading (regardless of the network), offline access, push notifications, and other capabilities.</p><p>Check <a href="https://caniuse.com/serviceworkers">https://caniuse.com/serviceworkers</a> for JavaScript Service Worker API availability based on WebView/Browser version.</p><p>Service workers are available on Android starting from “Android 5–6.x WebView: Chromium 107” and on iOS starting from iOS 14.0+.</p><p>On iOS, enabling the Service Worker API requires additional setup using App-Bound Domains (read the <a href="https://webkit.org/blog/10882/app-bound-domains/">WebKit — App-Bound Domains</a> article for more details).</p><p>The App-Bound Domains feature takes steps to preserve user privacy by limiting the domains on which an app can utilize powerful APIs to track users during in-app browsing.</p><p>You can specify up to ten “app-bound” domains using the Info.plist key WKAppBoundDomains.</p><p>So, we need to add the domain of our PWA to it. Otherwise, the Service Worker API will not work. For our use case, we need to add the mdn.github.io domain. Here is an example of the ios/Runner/Info.plist file:</p><pre>&lt;dict&gt;<br>  &lt;!-- ... --&gt;<br>  &lt;key&gt;WKAppBoundDomains&lt;/key&gt;<br>  &lt;array&gt;<br>    &lt;string&gt;mdn.github.io&lt;/string&gt;<br>  &lt;/array&gt;<br>  &lt;!-- ... --&gt;<br>&lt;/dict&gt;</pre><h4>Internet network detection</h4><p>Detecting whether the user&#39;s mobile phone is connected to the internet is important for WebView to load the PWA from the cache instead of requesting the resources online.</p><p>To check if there is a valid connection, that is, cellular network or Wi-Fi, we will use the <a href="https://pub.dev/packages/connectivity_plus">connectivity_plus</a> plugin. Instead, to test if the network is connected to internet, we can try to look up the address of a host, such as <a href="https://example.com/">https://example.com/</a>.</p><p>Here is the full code detection:</p><pre>Future&lt;bool&gt; isNetworkAvailable() async {<br>  // check if there is a valid network connection<br>  final connectivityResult = await Connectivity().checkConnectivity();<br>  if (connectivityResult != ConnectivityResult.mobile &amp;&amp;<br>      connectivityResult != ConnectivityResult.wifi) {<br>    return false;<br>  }<br><br>  // check if the network is really connected to Internet<br>  try {<br>    final result = await InternetAddress.lookup(&#39;example.com&#39;);<br>    if (result.isEmpty || result[0].rawAddress.isEmpty) {<br>      return false;<br>    }<br>  } on SocketException catch (_) {<br>    return false;<br>  }<br><br>  return true;<br>}</pre><h4>InAppWebView basic settings</h4><p>To make the InAppWebView work correctly, we need to set some basic settings:</p><pre>InAppWebViewSettings(<br>    // enable opening windows support<br>    supportMultipleWindows: true,<br>    javaScriptCanOpenWindowsAutomatically: true,<br><br>    // useful for identifying traffic, e.g. in Google Analytics.<br>    applicationNameForUserAgent: &#39;My PWA App Name&#39;,<br>    // Override the User Agent, otherwise some external APIs, such as Google and Facebook logins, will not work<br>    // because they recognize the default WebView User Agent.<br>    userAgent:<br>        &#39;Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.5304.105 Mobile Safari/537.36&#39;,<br><br>    disableDefaultErrorPage: true,<br><br>    // enable iOS service worker feature limited to defined App Bound Domains<br>    limitsNavigationsToAppBoundDomains: true<br>);</pre><p>Change it depending on your needs.</p><p>In this example, we are enabling support for multiple windows in case we want to open popup WebView windows.</p><p>In some cases, you may also need to override the user agent to a different value from the default one to be able to use some external APIs, such as Google and Facebook logins. Otherwise, they will not work because they recognize and block the default WebView user agent.</p><p>Also, you must set the limitsNavigationsToAppBoundDomains setting to true enable Service Worker API on iOS.</p><h4>HTTP (non-HTTPS) support</h4><p>Starting with Android 9 (API level 28), cleartext support is disabled by default:</p><ul><li>Check the official <a href="https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted">Network security configuration — “Opt out of cleartext traffic”</a> section.</li><li>Also, check this StackOverflow issue answer: <a href="https://stackoverflow.com/a/50834600/4637638">Cleartext HTTP traffic is not permitted</a>.</li></ul><p>On iOS, you need to disable <a href="https://developer.apple.com/documentation/security/preventing_insecure_network_connections">Apple Transport Security</a> (ATS) feature. There are two options:</p><ul><li>Disable ATS for a specific domain only (<a href="https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity/nsexceptiondomains">Official wiki</a>): (add the following code to your Info.plist file)</li></ul><pre>&lt;key&gt;NSAppTransportSecurity&lt;/key&gt;<br>&lt;dict&gt;<br>  &lt;key&gt;NSExceptionDomains&lt;/key&gt;<br>  &lt;dict&gt;<br>    &lt;key&gt;www.yourserver.com&lt;/key&gt;<br>    &lt;dict&gt;<br>      &lt;!-- add this key to enable subdomains such as sub.yourserver.com --&gt;<br>      &lt;key&gt;NSIncludesSubdomains&lt;/key&gt;<br>      &lt;true/&gt;<br>      &lt;!-- add this key to allow standard HTTP requests, thus negating the ATS --&gt;<br>      &lt;key&gt;NSTemporaryExceptionAllowsInsecureHTTPLoads&lt;/key&gt;<br>      &lt;true/&gt;<br>      &lt;!-- add this key to specify the minimum TLS version to accept --&gt;<br>      &lt;key&gt;NSTemporaryExceptionMinimumTLSVersion&lt;/key&gt;<br>      &lt;string&gt;TLSv1.1&lt;/string&gt;<br>    &lt;/dict&gt;<br>  &lt;/dict&gt;<br>&lt;/dict&gt;</pre><ul><li>Completely disable ATS (<a href="https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity/nsallowsarbitraryloads">Official wiki</a>). Add the following code to your Info.plist file:</li></ul><pre>&lt;key&gt;NSAppTransportSecurity&lt;/key&gt;<br>&lt;dict&gt;<br>  &lt;key&gt;NSAllowsArbitraryLoads&lt;/key&gt;&lt;true/&gt;<br>&lt;/dict&gt;</pre><p>Other useful Info.plist properties are:</p><ul><li>NSAllowsLocalNetworking: A Boolean value indicating whether to allow loading of local resources (<a href="https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity/nsallowslocalnetworking">Official wiki</a>)</li><li>NSAllowsArbitraryLoadsInWebContent: A Boolean value indicating whether all App Transport Security restrictions are disabled for requests made from web views (<a href="https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity/nsallowsarbitraryloadsinwebcontent">Official wiki</a>)</li></ul><h3>WidgetsBindingObserver</h3><p>Also, we are going to use the WidgetsBindingObserver for Android, useful to know when the system puts the app in the background or returns the app to the foreground.</p><p>With it, we can stop and resume JavaScript execution and any processing that can be paused safely, such as videos, audio, and animations.</p><p>Here is a simple implementation of didChangeAppLifecycleState:</p><pre>@override<br>void didChangeAppLifecycleState(AppLifecycleState state) {<br>  if (!kIsWeb) {<br>    if (webViewController != null &amp;&amp;<br>        defaultTargetPlatform == TargetPlatform.android) {<br>      if (state == AppLifecycleState.paused) {<br>        pauseAll();<br>      } else {<br>        resumeAll();<br>      }<br>    }<br>  }<br>}<br><br>void pauseAll() {<br>  if (defaultTargetPlatform == TargetPlatform.android) {<br>    webViewController?.pause();<br>  }<br>  webViewController?.pauseTimers();<br>}<br><br>void resumeAll() {<br>  if (defaultTargetPlatform == TargetPlatform.android) {<br>    webViewController?.resume();<br>  }<br>  webViewController?.resumeTimers();<br>}</pre><h3>WillPopScope</h3><p>To detect Android back button clicks, we wrap our main Scaffold widget app into a WillPopScope widget and implement the onWillPop method to go back in the history of WebView.</p><p>Here is an implementation example:</p><pre>@override<br>Widget build(BuildContext context) {<br>  return WillPopScope(<br>    onWillPop: () async {<br>      // detect Android back button click<br>      final controller = webViewController;<br>      if (controller != null) {<br>        if (await controller.canGoBack()) {<br>          controller.goBack();<br>          return false;<br>        }<br>      }<br>      return true;<br>    },<br>    child: Scaffold(<br>        appBar: AppBar(<br>          // remove the toolbar<br>          toolbarHeight: 0,<br>        ),<br>        body: // ...<br>    ),<br>  );<br>}</pre><h3>WebView PWA Wrapper</h3><p>Before loading the PWA URL inside the InAppWebView wrapper, we check if the internet connection is available using the utility defined before, and, based on it, we need to set the cache mode and policy for Android and iOS this way:</p><pre>// Android-only<br>final cacheMode = networkAvailable<br>    ? CacheMode.LOAD_DEFAULT<br>    : CacheMode.LOAD_CACHE_ELSE_NETWORK;<br><br>// iOS-only<br>final cachePolicy = networkAvailable<br>    ? URLRequestCachePolicy.USE_PROTOCOL_CACHE_POLICY<br>    : URLRequestCachePolicy.RETURN_CACHE_DATA_ELSE_LOAD;</pre><p>The cacheMode will be used in the initialSettings property and the cachePolicy will be used in the URLRequest of the initialUrlRequest property.</p><p>This logic allows us to load cached data if an unavailable internet connection.</p><p>To restrict navigation to the PWA host only, we implement the shouldOverrideUrlLoading method to check if a specific HTTP request for the main frame doesn’t match the PWA host, so we will open that request in third-party apps using the <a href="https://pub.dev/packages/url_launcher">url_launcher</a> plugin:</p><pre>shouldOverrideUrlLoading:<br>    (controller, navigationAction) async {<br>  // restrict navigation to target host, open external links in 3rd party apps<br>  final uri = navigationAction.request.url;<br>  if (uri != null &amp;&amp;<br>      navigationAction.isForMainFrame &amp;&amp;<br>      uri.host != kPwaHost &amp;&amp;<br>      await canLaunchUrl(uri)) {<br>    launchUrl(uri);<br>    return NavigationActionPolicy.CANCEL;<br>  }<br>  return NavigationActionPolicy.ALLOW;<br>},</pre><p>To detect if the PWA has been “installed” correctly the first time, we implement the onLoadStop WebView method to check the internet connection availability and if the PWA has already been installed:</p><pre>onLoadStop: (controller, url) async {<br>  if (await isNetworkAvailable() &amp;&amp; !(await isPWAInstalled())) {<br>    // if network is available and this is the first time<br>    setPWAInstalled();<br>  }<br>},</pre><p>The two utilities, isPWAInstalled and setPWAInstalled, could be implemented as follow using the <a href="https://pub.dev/packages/shared_preferences">shared_preferences</a> plugin to get and save the PWA installation status:</p><pre>Future&lt;bool&gt; isPWAInstalled() async {<br>  final prefs = await SharedPreferences.getInstance();<br>  return prefs.getBool(&#39;isInstalled&#39;) ?? false;<br>}<br><br>void setPWAInstalled({bool installed = true}) async {<br>  final prefs = await SharedPreferences.getInstance();<br>  await prefs.setBool(&#39;isInstalled&#39;, installed);<br>}</pre><p>All these utilities allow us to detect network availability and installation status of the PWA so that we can implement a custom error page, as below:</p><pre>onReceivedError: (controller, request, error) async {<br>  final isForMainFrame = request.isForMainFrame ?? true;<br>  if (isForMainFrame &amp;&amp; !(await isNetworkAvailable())) {<br>    if (!(await isPWAInstalled())) {<br>      await controller.loadData(<br>          data: kHTMLErrorPageNotInstalled);<br>    }<br>  }<br>},</pre><p>where kHTMLErrorPageNotInstalled is a String containing our custom HTML.</p><p>If you need to support the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API">Web Notification JavaScript API</a>, unfortunately, Android-native WebView and iOS-native WKWebView don’t support that feature natively, so we must implement it ourselves! For an example implementation, you can check the <a href="https://github.com/pichillilorenzo/flutter_inappwebview_examples/tree/main/web_notification">Web Notification project example</a>. It uses a <a href="https://inappwebview.dev/docs/webview/javascript/user-scripts">UserScript</a> to inject custom JavaScript code at web page startup to implement the Web Notification API.</p><p>The injected JavaScript code tries to create a “polyfill” for the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Notification">Notification</a> window object and communicate with Flutter/Dart side using <a href="https://inappwebview.dev/docs/webview/javascript/communication#JavaScript-Handlers">JavaScript Handlers</a> to manage and implement the corresponding Notification UI, for example, when you are requesting permission with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Notification/requestPermission">Notification.requestPermission()</a> or when you want to show a notification.</p><p>Also, if you need to support the usage of the camera and microphone (for example, a WebRTC App), you need to implement the onPermissionRequest event and ask for permissions using, for example, the <a href="https://pub.dev/packages/permission_handler">permission_handler</a> plugin. For more details, visit the <a href="https://inappwebview.dev/docs/web-rtc">official WebRTC guide</a> and the <a href="https://github.com/pichillilorenzo/flutter_inappwebview_examples/tree/main/webrtc">WebRTC project example</a>.</p><p>To manage requests that open a new window using JavaScript (window.open()) or by the target attribute in a link (such as target=&quot;_blank&quot;), we must implement the onCreateWindow event and return true to declare that we are handling the request. Here is a simple example:</p><pre>onCreateWindow: (controller, createWindowAction) async {<br>  showDialog(<br>    context: context,<br>    builder: (context) {<br>      final popupWebViewSettings =<br>          sharedSettings.copy();<br>      popupWebViewSettings.supportMultipleWindows =<br>          false;<br>      popupWebViewSettings<br>              .javaScriptCanOpenWindowsAutomatically =<br>          false;<br><br>      return WebViewPopup(<br>          createWindowAction: createWindowAction,<br>          popupWebViewSettings: popupWebViewSettings);<br>    },<br>  );<br>  return true;<br>},</pre><p>The WebViewPopup is another InAppWebView instance inside an AlertDialog widget that takes in input the createWindowAction to get the windowId to use for the new WebView. The windowId is an identifier used on the native side to get the right WebView reference that Flutter must show. The WebView Popup will also implement the onCloseWindow to listen when the popup should be closed and removed from the Widget tree:</p><pre>onCloseWindow: (controller) {<br>  Navigator.pop(context);<br>},</pre><p>Check also the <a href="https://github.com/pichillilorenzo/flutter_inappwebview_examples/tree/main/popup_window">Popup Window project example</a> for an example implementation.</p><p>To implement our two-way communication between JavaScript and Flutter/Dart side, we will use the <a href="https://inappwebview.dev/docs/webview/javascript/communication#JavaScript-Handlers">JavaScript Handlers</a> feature.</p><p>For our use case, we want listen for clicks on the “Request dummy notifications” button HTML element with id notifications and show a SnackBar with the random text generated by JavaScript.</p><p>To do that, we create a simple <a href="https://inappwebview.dev/docs/webview/javascript/user-scripts">User Script</a> and inject it after the page is loaded:</p><pre>initialUserScripts: UnmodifiableListView&lt;UserScript&gt;([<br>  UserScript(<br>      source: &quot;&quot;&quot;<br>      document.getElementById(&#39;notifications&#39;).addEventListener(&#39;click&#39;, function(event) {<br>        var randomText = Math.random().toString(36).slice(2, 7);<br>        window.flutter_inappwebview.callHandler(&#39;requestDummyNotification&#39;, randomText);<br>      });<br>      &quot;&quot;&quot;,<br>      injectionTime:<br>          UserScriptInjectionTime.AT_DOCUMENT_END)<br>]),</pre><p>Then, we add the corresponding JavaScript Handler right after when the WebView instance is created:</p><pre>onWebViewCreated: (controller) {<br>  webViewController = controller;<br><br>  controller.addJavaScriptHandler(<br>    handlerName: &#39;requestDummyNotification&#39;,<br>    callback: (arguments) {<br>      final String randomText =<br>          arguments.isNotEmpty ? arguments[0] : &#39;&#39;;<br>      ScaffoldMessenger.of(context).showSnackBar(<br>          SnackBar(content: Text(randomText)));<br>    },<br>  );<br>},</pre><p>Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*2t9L1UObcsrKYRRmKTGngw.gif" /><figcaption>Android example result.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*ICiUmH2pjITByEDwMhIPzg.gif" /><figcaption>iOS example result.</figcaption></figure><p>The full code project example is available at <a href="https://github.com/pichillilorenzo/flutter_inappwebview_examples/tree/main/pwa_to_flutter_app">https://github.com/pichillilorenzo/flutter_inappwebview_examples/tree/main/pwa_to_flutter_app</a></p><p>That’s all for today!</p><p>Are you using this plugin? Submit your app through the <a href="https://inappwebview.dev/submit-app/">Submit App</a> page and follow the instructions. Check the <a href="https://inappwebview.dev/showcase/">Showcase</a> page to see who is already using it!</p><p><em>This project follows the </em><a href="https://github.com/all-contributors/all-contributors"><em>all-contributors</em></a><em> specification (</em><a href="https://github.com/pichillilorenzo/flutter_inappwebview#contributors-"><em>contributors</em></a><em>). I want to thank all the people that are supporting the project in any way. Thanks a lot to all of you! </em>💙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=387060548a37" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/convert-a-pwa-into-a-flutter-app-using-webviews-387060548a37">Convert a PWA Into a Flutter App Using WebViews</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Injecting JavaScript in Flutter Web View With User Scripts]]></title>
            <link>https://medium.com/better-programming/webview-javascript-injection-with-user-scripts-flutter-inappwebview-6-46d9969353a4?source=rss-11e6aac5f656------2</link>
            <guid isPermaLink="false">https://medium.com/p/46d9969353a4</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Lorenzo Pichilli]]></dc:creator>
            <pubDate>Mon, 28 Nov 2022 20:53:30 GMT</pubDate>
            <atom:updated>2022-11-29T11:40:58.085Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to leverage Flutter’s InAppWebView 6 plugin</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VGdKluhbwdJg29P8" /><figcaption>Photo by <a href="https://unsplash.com/@rahuulmiishra?utm_source=medium&amp;utm_medium=referral">Rahul Mishra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Sometimes you may want to inject JavaScript code before or after the web page is loaded in order to add, replace or remove content from the web page or to change some web page logic.</p><p>In this article, we are going to understand what User Scripts are and how we can use them to inject custom JavaScript code at a specific time inside the WebView using the <a href="https://github.com/pichillilorenzo/flutter_inappwebview">flutter_inappwebview</a> plugin.</p><h3>The UserScript class</h3><p>The UserScript class is the equivalent of the <a href="https://developer.apple.com/documentation/webkit/wkuserscript">WKUserScript</a> native class. It represents a JavaScript code that the WebView injects into the web page and in any other subsequent navigated web page.</p><p>What are the advantages of using User Scripts instead of just injecting some JavaScript code like, for example, the evaluateJavascript method?</p><p>An UserScript gives you the possibility to inject a JavaScript code before other resources of the web page is loaded, setting the injectionTime property to UserScriptInjectionTime.AT_DOCUMENT_START.</p><p>For each UserScript, you can set an optional <a href="https://inappwebview.dev/docs/webview/javascript/content-worlds/">Content World</a>, set whether to inject the script into the main frame using the forMainFrameOnly property (iOS/macOS only), and a set of matching rules for the allowed origins (Android only).</p><h4>Note for Android</h4><p>Unfortunately, on Android, when using UserScriptInjectionTime.AT_DOCUMENT_START, if the WebViewFeature.DOCUMENT_START_SCRIPT is not supported, there is no guarantee that the JavaScript code has been injected before other resources are loaded because the corresponding native class/feature doesn&#39;t exist, so InAppWebView tries to inject that UserScript as soon as possible.</p><p>To add a UserScript to a WebView, you can use the WebView.initialUserScripts property:</p><pre>InAppWebView(<br>  initialUrlRequest: URLRequest(url: WebUri(&#39;https://flutter.dev&#39;)),<br>  initialUserScripts: UnmodifiableListView&lt;UserScript&gt;([<br>    UserScript(<br>        source: &quot;var foo = 49;&quot;,<br>        injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),<br>    UserScript(<br>        source: &quot;var bar = 2;&quot;,<br>        injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END),<br>  ]),<br>  onLoadStop: (controller, url) async {<br>    var result = await controller.evaluateJavascript(source: &quot;foo + bar&quot;);<br>    print(result); // 51<br>  },<br>),</pre><p>For each UserScript you can set the following properties:</p><ul><li>groupName: The script’s group name.</li><li>source: The script’s source code.</li><li>injectionTime: The time at which to inject the script into the WebView. It can be UserScriptInjectionTime.AT_DOCUMENT_START or UserScriptInjectionTime.AT_DOCUMENT_END.</li><li>forMainFrameOnly: A Boolean value that indicates whether to inject the script into the main frame. Specify true to inject the script only into the main frame, or false to inject it into all frames. The default value is true.</li><li>allowedOriginRules: A set of matching rules for the allowed origins. Available only on Android and only if WebViewFeature.DOCUMENT_START_SCRIPT feature is supported.</li><li>contentWorld: A scope of execution in which to evaluate the script to prevent conflicts between different scripts.</li></ul><p>Check the code documentation for each specific property to know which platform supports that feature.</p><p>To add or remove User Scripts at runtime, you can also use the corresponding methods, such as InAppWebViewController.addUserScript, InAppWebViewController.removeUserScript, etc.</p><p>Note that adding or removing User Scripts at runtime, after a web page is loaded, will take no effect until the next web page load.</p><p>Also, for each UserScript you can define a groupName that you can use, for example, to remove a group of User Scripts with the InAppWebViewController.removeUserScriptsByGroupName method.</p><p>This is a simple overview of what it’s like to add basic User Scripts to a WebView.</p><p>But, what can a User Script do?</p><p>It can do anything a normal script on the webpage can do, such as modify the HTML document structure, listen to events like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event">onload</a>, load external resources (images, <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">fetch</a>, etc…). You can also communicate back with Flutter/Dart side (check the <a href="https://inappwebview.dev/docs/webview/javascript/communication">official JavaScript Communication docs</a> for more info).</p><p>Let’s put what we’ve learned into practice with an example!</p><h3>User Scripts example</h3><p>In this example, we load the <a href="https://example.com/">https://example.com</a> web page with 3 custom user scripts to change some CSS styles and add some logic using a javascript handler for the two-way communication with Flutter/Dart side.</p><pre>import &#39;dart:async&#39;;<br>import &#39;dart:collection&#39;;<br>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_inappwebview/flutter_inappwebview.dart&#39;;<br><br>final userScript1 = UserScript(<br>    groupName: &quot;myUserScripts&quot;,<br>    source: &quot;&quot;&quot;<br>window.addEventListener(&#39;load&#39;, function(event) {<br>  document.body.style.backgroundColor = &#39;blue&#39;;<br>  document.body.style.padding = &#39;20px&#39;;<br>});<br>&quot;&quot;&quot;,<br>    injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START);<br><br>final userScript2 = UserScript(<br>    groupName: &quot;myUserScripts&quot;,<br>    source: &quot;&quot;&quot;<br>var h1 = document.querySelector(&#39;h1&#39;);<br>h1.addEventListener(&#39;click&#39;, function(event) {<br>  window.flutter_inappwebview.callHandler(&#39;h1Click&#39;, h1.innerText);<br>});<br>&quot;&quot;&quot;,<br>    injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END);<br><br>final userScript3 = UserScript(<br>    groupName: &quot;myUserScripts&quot;,<br>    source: &quot;document.querySelector(&#39;h1&#39;).innerHTML = &#39;Custom Title&#39;;&quot;,<br>    injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END);<br><br>Future main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  if (!kIsWeb &amp;&amp;<br>      kDebugMode &amp;&amp;<br>      defaultTargetPlatform == TargetPlatform.android) {<br>    await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);<br>  }<br>  runApp(const MaterialApp(home: MyApp()));<br>}<br><br>class MyApp extends StatefulWidget {<br>  const MyApp({Key? key}) : super(key: key);<br><br>  @override<br>  _MyAppState createState() =&gt; _MyAppState();<br>}<br><br>class _MyAppState extends State&lt;MyApp&gt; {<br>  final GlobalKey webViewKey = GlobalKey();<br><br>  InAppWebViewController? webViewController;<br><br>  void handleClick(int item) async {<br>    switch (item) {<br>      case 0:<br>        await webViewController?.removeAllUserScripts();<br>        break;<br>      case 1:<br>        await webViewController?.addUserScript(userScript: userScript1);<br>        break;<br>      case 2:<br>        await webViewController?.removeUserScript(userScript: userScript1);<br>        break;<br>      case 3:<br>        await webViewController?.addUserScript(userScript: userScript2);<br>        break;<br>      case 4:<br>        await webViewController?.removeUserScript(userScript: userScript2);<br>        break;<br>      case 5:<br>        await webViewController?.addUserScript(userScript: userScript3);<br>        break;<br>      case 6:<br>        await webViewController?.removeUserScript(userScript: userScript3);<br>        break;<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>        appBar: AppBar(<br>          title: const Text(&quot;User Scripts&quot;),<br>          actions: &lt;Widget&gt;[<br>            IconButton(<br>                onPressed: () {<br>                  webViewController?.reload();<br>                },<br>                icon: const Icon(Icons.refresh)),<br>            PopupMenuButton&lt;int&gt;(<br>              onSelected: (item) =&gt; handleClick(item),<br>              itemBuilder: (context) =&gt; [<br>                const PopupMenuItem&lt;int&gt;(<br>                    value: 0, child: Text(&#39;Remove User Scripts&#39;)),<br>                const PopupMenuItem&lt;int&gt;(<br>                    value: 1, child: Text(&#39;Add User Script 1&#39;)),<br>                const PopupMenuItem&lt;int&gt;(<br>                    value: 2, child: Text(&#39;Remove User Script 1&#39;)),<br>                const PopupMenuItem&lt;int&gt;(<br>                    value: 3, child: Text(&#39;Add User Script 2&#39;)),<br>                const PopupMenuItem&lt;int&gt;(<br>                    value: 4, child: Text(&#39;Remove User Script 2&#39;)),<br>                const PopupMenuItem&lt;int&gt;(<br>                    value: 5, child: Text(&#39;Add User Script 3&#39;)),<br>                const PopupMenuItem&lt;int&gt;(<br>                    value: 6, child: Text(&#39;Remove User Script 3&#39;)),<br>              ],<br>            ),<br>          ],<br>        ),<br>        body: Column(children: &lt;Widget&gt;[<br>          Expanded(<br>            child: Stack(<br>              children: [<br>                InAppWebView(<br>                  key: webViewKey,<br>                  initialUrlRequest:<br>                      URLRequest(url: WebUri(&#39;https://example.com&#39;)),<br>                  initialUserScripts: UnmodifiableListView&lt;UserScript&gt;(<br>                      [userScript1, userScript2, userScript3]),<br>                  onWebViewCreated: (controller) {<br>                    webViewController = controller;<br>                    controller.addJavaScriptHandler(<br>                        handlerName: &#39;h1Click&#39;,<br>                        callback: (arguments) {<br>                          final String h1InnerText = arguments[0];<br>                          showDialog(<br>                            context: context,<br>                            builder: (context) {<br>                              return AlertDialog(<br>                                title: const Text(&#39;h1 clicked&#39;),<br>                                content: Text(h1InnerText),<br>                              );<br>                            },<br>                          );<br>                        });<br>                  },<br>                ),<br>              ],<br>            ),<br>          ),<br>        ]));<br>  }<br>}</pre><p>Use the action buttons on the top right to remove or add the user scripts and then reload the web page for the changes to take effect.</p><p>Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*847T12eD6DEbT8fe5DveBg.gif" /><figcaption>WebView User Scripts example.</figcaption></figure><p>WebView offers powerful tools to manipulate JavaScript and the User Script feature is one of these.</p><p>That’s all for today!</p><p>If this project helps you in any way, please consider <a href="https://inappwebview.dev/donate">making a donation</a>!</p><p>Are you using this plugin? Submit your app through the <a href="https://inappwebview.dev/submit-app/">Submit App</a> page and follow the instructions.<br>Check the <a href="https://inappwebview.dev/showcase/">Showcase</a> page to see who is already using it!</p><p><em>This project follows the </em><a href="https://github.com/all-contributors/all-contributors"><em>all-contributors</em></a><em> specification (</em><a href="https://github.com/pichillilorenzo/flutter_inappwebview#contributors-"><em>contributors</em></a><em>). I want to thank all the people that are supporting the project in any way. Thanks a lot to all of you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46d9969353a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/webview-javascript-injection-with-user-scripts-flutter-inappwebview-6-46d9969353a4">Injecting JavaScript in Flutter Web View With User Scripts</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebView Content Blockers — Flutter InAppWebView 6]]></title>
            <link>https://medium.com/@pichillilorenzo/webview-content-blockers-flutter-inappwebview-6-faba4d61c294?source=rss-11e6aac5f656------2</link>
            <guid isPermaLink="false">https://medium.com/p/faba4d61c294</guid>
            <category><![CDATA[ad-blocking]]></category>
            <category><![CDATA[content-blocking]]></category>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-webview]]></category>
            <dc:creator><![CDATA[Lorenzo Pichilli]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 12:07:18 GMT</pubDate>
            <atom:updated>2022-11-27T12:36:31.282Z</atom:updated>
            <content:encoded><![CDATA[<h3>WebView Content Blockers — Flutter InAppWebView 6</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SmgWPCjsu9AX6AtN" /><figcaption>Photo by <a href="https://unsplash.com/@sammy?utm_source=medium&amp;utm_medium=referral">Samuel Schroth</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we are going to understand how to create a custom Content Blocker for our WebView instances using the <a href="https://github.com/pichillilorenzo/flutter_inappwebview">flutter_inappwebview</a> plugin.</p><p>Content Blockers are usually used for blocking ads, but you can also block any other content. Blocking behaviors include hiding elements, blocking loads, and, on iOS and macOS, stripping cookies from the WebView requests.</p><p>Keep in mind that, in general, Content Blockers cannot achieve the same level of functionalities as specialized extensions such as AdBlock or AdBlock Plus. Content Blockers are a set of rules that will never get any callbacks or notifications back from the WebView when it finds content it needs to block.</p><p>Through the contentBlockers property of the InAppWebViewSettings class, we can define a list of ContentBlocker instances that the WebView will use.</p><h3>The ContentBlocker class</h3><p>The ContentBlocker class is the class in which we define content-blocking behavior. Each one contains an <strong>action</strong> property and a <strong>trigger</strong> property. The action tells the WebView what to do when it encounters a match for the trigger. The trigger tells the WebView when to perform the corresponding action.</p><p>Here is a basic example:</p><pre>initialSettings: InAppWebViewSettings(contentBlockers: [<br>  ContentBlocker(<br>    trigger: ContentBlockerTrigger(<br>      urlFilter: &quot;.*&quot;,<br>      resourceType: [<br>        ContentBlockerTriggerResourceType.IMAGE,<br>        ContentBlockerTriggerResourceType.STYLE_SHEET<br>      ]<br>    ),<br>    action: ContentBlockerAction(<br>      type: ContentBlockerActionType.BLOCK<br>    )<br>  )<br>]),</pre><p>In this example, we are saying to block the load of every image and stylesheet for every URL.</p><h3>Add triggers to your Content Blocker</h3><p>A trigger must define the required urlFilter property, which specifies a regular expression as a string to match the URL against. The other properties are optional and modify the behavior of the trigger. For example, you can limit the trigger to specific domains or have it not apply when the WebView finds a match for a specific domain.</p><p>Here is an example of a Content Blocker with a trigger for image and style sheet resources that the WebView finds on any domain except those specified:</p><pre>initialSettings: InAppWebViewSettings(contentBlockers: [<br>  ContentBlocker(<br>    trigger: ContentBlockerTrigger(<br>      urlFilter: &quot;.*&quot;,<br>      resourceType: [<br>        ContentBlockerTriggerResourceType.IMAGE,<br>        ContentBlockerTriggerResourceType.STYLE_SHEET<br>      ],<br>      unlessDomain: [&quot;example.com&quot;, &quot;github.com&quot;, &quot;pub.dev&quot;]<br>    ),<br>    action: ContentBlockerAction(<br>      type: ContentBlockerActionType.BLOCK<br>    )<br>  )<br>]),</pre><p>For deeper trigger customization, you can use the other properties of ContentBlockerTrigger :</p><ul><li>urlFilterIsCaseSensitive: <em>If the URL matching should be case-sensitive. By default, it is case insensitive.</em></li><li>resourceType: <em>A list of “ContentBlockerTriggerResourceType” representing the resource types (how the browser intends to use the resource) that the rule should match. If not specified, the rule matches all resource types.</em></li><li>ifDomain: <em>A list of strings matched to a URL’s domain; limits action to a list of specific domains. Values must be lowercase ASCII, or punycode for non-ASCII. Add * in front to match domain and subdomains. It can’t be used with “unlessDomain”.</em></li><li>unlessDomain: <em>A list of strings matched to a URL’s domain; acts on any site except domains in a provided list. Values must be lowercase ASCII, or punycode for non-ASCII. Add * in front to match domain and subdomains. It can’t be used with “ifDomain”.</em></li><li>loadType: <em>A list of “ContentBlockerTriggerLoadType” that can include one of two mutually exclusive values. If not specified, the rule matches all load types. “ContentBlockerTriggerLoadType.FIRST_PARTY” triggers only if the resource has the same scheme, domain, and port as the main page resource. “ContentBlockerTriggerLoadType.THIRD_PARTY” triggers if the resource isn’t from the same domain as the main page resource.</em></li><li>ifTopUrl: <em>A list of strings matched to the entire main document URL; limits the action to a specific list of URL patterns. Values must be lowercase ASCII, or punycode for non-ASCII. It can’t be used with “unlessTopUrl”.</em></li><li>unlessTopUrl: <em>An array of strings matched to the entire main document URL; acts on any site except URL patterns in the provided list. Values must be lowercase ASCII, or punycode for non-ASCII. It can’t be used with “ifTopUrl”.</em></li><li>loadContext: <em>An array of strings that specify loading contexts.</em></li><li>ifFrameUrl: <em>A list of regular expressions to match iframes URL against.</em></li></ul><p>Check the code documentation for each specific property to know which platform supports that feature.</p><h3>Add actions to your Content Blocker</h3><p>When a trigger matches a resource, the WebView evaluates all the triggers and executes the actions in order.</p><p>Group the rules with similar actions together to improve performance. For example, first specify rules that block content loading, followed by rules that block cookies.</p><p>There are only two valid properties for actions: type and selector. An action type is required.<br>If the type is ContentBlockerActionType.CSS_DISPLAY_NONE, a selector is required as well; otherwise, the selector is optional.</p><p>Here is a simple example:</p><pre>initialSettings: InAppWebViewSettings(contentBlockers: [<br>  ContentBlocker(<br>    trigger: ContentBlockerTrigger(<br>      urlFilter: &quot;https://flutter.dev/.*&quot;,<br>    ),<br>    action: ContentBlockerAction(<br>      type: ContentBlockerActionType.CSS_DISPLAY_NONE,<br>      selector: &#39;.notification, .media, #developer-story&#39;<br>    )<br>  )<br>]),</pre><p>Valid types are:</p><ul><li>BLOCK: <em>Stops loading of the resource. If the resource was cached, the cache is ignored.</em></li><li>BLOCK_COOKIES: <em>Strips cookies from the header before sending it to the server. This only blocks cookies otherwise acceptable to WebView’s privacy policy. Combining with “IGNORE_PREVIOUS_RULES” doesn’t override the browser’s privacy settings.</em></li><li>CSS_DISPLAY_NONE: <em>Hides elements of the page based on a CSS selector. A selector field contains the selector list. Any matching element has its display property set to none, which hides it.</em></li><li>MAKE_HTTPS: <em>Changes a URL from http to https. URLs with a specified (nondefault) port and links using other protocols are unaffected.</em></li><li>IGNORE_PREVIOUS_RULES: <em>Ignores previously triggered actions.</em></li></ul><p>Check the code documentation for each specific type to know which platform supports it.</p><h3>Creating a simple Ad Blocker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hIIdJsDzAGpIf9fl" /><figcaption>Photo by <a href="https://unsplash.com/@katetrysh?utm_source=medium&amp;utm_medium=referral">Kate Trysh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s create a simple <strong>ad blocker</strong> using what we have learned.</p><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_inappwebview/flutter_inappwebview.dart&#39;;<br><br>Future main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  if (!kIsWeb &amp;&amp;<br>      kDebugMode &amp;&amp;<br>      defaultTargetPlatform == TargetPlatform.android) {<br>    await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);<br>  }<br>  runApp(const MaterialApp(home: MyApp()));<br>}<br><br>class MyApp extends StatefulWidget {<br>  const MyApp({Key? key}) : super(key: key);<br><br>  @override<br>  State&lt;MyApp&gt; createState() =&gt; _MyAppState();<br>}<br><br>class _MyAppState extends State&lt;MyApp&gt; {<br>  final GlobalKey webViewKey = GlobalKey();<br><br>  // list of Ad URL filters to be used to block ads loading.<br>  final adUrlFilters = [<br>    &quot;.*.doubleclick.net/.*&quot;,<br>    &quot;.*.ads.pubmatic.com/.*&quot;,<br>    &quot;.*.googlesyndication.com/.*&quot;,<br>    &quot;.*.google-analytics.com/.*&quot;,<br>    &quot;.*.adservice.google.*/.*&quot;,<br>    &quot;.*.adbrite.com/.*&quot;,<br>    &quot;.*.exponential.com/.*&quot;,<br>    &quot;.*.quantserve.com/.*&quot;,<br>    &quot;.*.scorecardresearch.com/.*&quot;,<br>    &quot;.*.zedo.com/.*&quot;,<br>    &quot;.*.adsafeprotected.com/.*&quot;,<br>    &quot;.*.teads.tv/.*&quot;,<br>    &quot;.*.outbrain.com/.*&quot;<br>  ];<br><br>  final List&lt;ContentBlocker&gt; contentBlockers = [];<br>  var contentBlockerEnabled = true;<br><br>  InAppWebViewController? webViewController;<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    // for each Ad URL filter, add a Content Blocker to block its loading.<br>    for (final adUrlFilter in adUrlFilters) {<br>      contentBlockers.add(ContentBlocker(<br>          trigger: ContentBlockerTrigger(<br>            urlFilter: adUrlFilter,<br>          ),<br>          action: ContentBlockerAction(<br>            type: ContentBlockerActionType.BLOCK,<br>          )));<br>    }<br><br>    // apply the &quot;display: none&quot; style to some HTML elements<br>    contentBlockers.add(ContentBlocker(<br>        trigger: ContentBlockerTrigger(<br>          urlFilter: &quot;.*&quot;,<br>        ),<br>        action: ContentBlockerAction(<br>            type: ContentBlockerActionType.CSS_DISPLAY_NONE,<br>            selector: &quot;.banner, .banners, .ads, .ad, .advert&quot;)));<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>        appBar: AppBar(<br>          title: const Text(&quot;Ads Content Blocker&quot;),<br>          actions: [<br>            TextButton(<br>              onPressed: () async {<br>                contentBlockerEnabled = !contentBlockerEnabled;<br>                if (contentBlockerEnabled) {<br>                  await webViewController?.setSettings(<br>                      settings: InAppWebViewSettings(<br>                          contentBlockers: contentBlockers));<br>                } else {<br>                  await webViewController?.setSettings(<br>                      settings: InAppWebViewSettings(contentBlockers: []));<br>                }<br>                webViewController?.reload();<br><br>                setState(() {});<br>              },<br>              style: TextButton.styleFrom(foregroundColor: Colors.white),<br>              child: Text(contentBlockerEnabled ? &#39;Disable&#39; : &#39;Enable&#39;),<br>            )<br>          ],<br>        ),<br>        body: SafeArea(<br>            child: Column(children: &lt;Widget&gt;[<br>          Expanded(<br>            child: Stack(<br>              children: [<br>                InAppWebView(<br>                  key: webViewKey,<br>                  initialUrlRequest:<br>                      URLRequest(url: WebUri(&#39;https://www.tomshardware.com/&#39;)),<br>                  initialSettings:<br>                      InAppWebViewSettings(contentBlockers: contentBlockers),<br>                  onWebViewCreated: (controller) {<br>                    webViewController = controller;<br>                  },<br>                ),<br>              ],<br>            ),<br>          ),<br>        ])));<br>  }<br>}</pre><p>Using these rules will prevent a bunch of ads to appear, such as Google Ads.</p><p>Click the Disable/Enable button to disable or enable the Ad Blocker feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*OMyptoJ4_jMVquCuKwTURQ.gif" /><figcaption>WebView Ad Blocker example.</figcaption></figure><h3>Conclusion</h3><p>Content Blockers allow us to write performant rules for blocking content in the WebView while respecting the user’s privacy.</p><p>Full project code is available at: <a href="https://github.com/pichillilorenzo/flutter_inappwebview_examples/tree/main/webview_ad_blocker">https://github.com/pichillilorenzo/flutter_inappwebview_examples/tree/main/webview_ad_blocker</a></p><p>That’s all for today!</p><p>If this project helps you in any way, please consider <a href="https://inappwebview.dev/donate">making a donation</a>!</p><p>Are you using this plugin? Submit your app through the <a href="https://inappwebview.dev/submit-app/">Submit App</a> page and follow the instructions.<br>Check the <a href="https://inappwebview.dev/showcase/">Showcase</a> page to see who is already using it!</p><p>This project follows the <a href="https://github.com/all-contributors/all-contributors">all-contributors</a> specification (<a href="https://github.com/pichillilorenzo/flutter_inappwebview#contributors-">contributors</a>). I want to thank all the people that are supporting the project in any way. Thanks a lot to all of you! 💙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faba4d61c294" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter InAppWebView 6]]></title>
            <link>https://medium.com/@pichillilorenzo/flutter-inappwebview-6-b0bcef5ca3cf?source=rss-11e6aac5f656------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0bcef5ca3cf</guid>
            <category><![CDATA[flutter-webview]]></category>
            <category><![CDATA[in-app-browsers]]></category>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Lorenzo Pichilli]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 19:06:16 GMT</pubDate>
            <atom:updated>2023-11-30T09:24:57.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*U0OTQU8dK5btGvDL57Ccbw.png" /></figure><p><a href="https://github.com/pichillilorenzo/flutter_inappwebview">Flutter InAppWebView 6</a> is out right now with a lot of new cool features and a fresh <a href="https://inappwebview.dev/">new website</a> built using <a href="https://docusaurus.io/">Docusaurus 2.0</a>! 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Z4DjteGr1kNVLS6guDzMA.png" /><figcaption>New InAppWebView website.</figcaption></figure><p>Let’s start diving into it!</p><h3>Migrating from version 5.x.x</h3><p>Version 6.x.x now requires the minimum Flutter version to be 3.0.0, Android minSdkVersion to be 19 (android/app/build.gradle), and the minimum iOS version to be 9.0 (ios/Podfile) with XCode version &gt;= 14.</p><p>Check the online <a href="https://inappwebview.dev/docs/migration-guide">Migration guide</a> for more details.</p><h3>Codebase refactoring</h3><p>There was a huge codebase refactoring, on both dart and native sides, to be able to implement and support other features and platform implementations.</p><p>This will help a lot when Desktop support will be available.</p><h3>Web Support</h3><p>This new version, finally, adds Web platform support!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*7BOnssyKl007NspkDC3g2A.gif" /></figure><p>The implementation uses the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe">iframe</a> HTML element under the hood, so it comes with a lot of <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#cross-origin_script_api_access">restrictions and limitations</a> regarding JavaScript execution and feature implementations.</p><p>So, unfortunately, most of the implemented WebView controllers methods require the iframe to have the same origin as the website, otherwise, they won’t work!</p><p>To correctly setup the Web platform, you need to add the web_support.js file inside the &lt;head&gt; of your web/index.html file:</p><pre>&lt;head&gt;<br>  &lt;!-- ... --&gt;<br>    &lt;script type=&quot;application/javascript&quot; src=&quot;/assets/packages/flutter_inappwebview_web/assets/web/web_support.js&quot; defer&gt;&lt;/script&gt;<br>  &lt;!-- ... --&gt;<br>&lt;/head&gt;</pre><p>To enable WebRTC, you need to set the Web-specific setting iframeAllow to camera; microphone, for example:</p><pre>initialSettings: InAppWebViewSettings(<br> iframeAllow: “camera; microphone”, <em>// for camera and microphone permissions</em><br> iframeAllowFullscreen: true, <em>// if you need fullscreen support</em><br>),</pre><p>Check more on <a href="https://inappwebview.dev/docs/intro#setup-web">Getting Started — Setup Web</a>.</p><h3>MacOS Support</h3><p>Also, this version adds MacOS platform support!</p><p>The current MacOS WebView implementations are the InAppBrowser and HeadlessWebView classes.</p><p>To be able to make HTTP requests, you need to configure the macOS App Sandbox by enabling the Outgoing Connections (Client) option in your MacOS XCode Project, under Runner &gt; Signing &amp; Capabilities.</p><p>To customize the InAppBrowser instance, use the settings in InAppBrowserSettings , such as windowType, windowAlphaValue, windowStyleMask, windowTitlebarSeparatorStyle, windowFrame .</p><p>Here is an example of the InAppBrowser implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*g8Nz_JKJjFXzJkpFCc8anw.gif" /></figure><p>Check more on <a href="https://inappwebview.dev/docs/intro/#setup-macos">Getting Started — Setup MacOS</a>.</p><p>To track general Desktop support, check <a href="https://github.com/pichillilorenzo/flutter_inappwebview/issues/460">#460</a>.</p><h3>New cool features</h3><p>As you can see from the <a href="https://github.com/pichillilorenzo/flutter_inappwebview/blob/master/CHANGELOG.md">CHANGELOG</a>, there are so many new features!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*_27Ir2wSdMzBRyo_h_Ri7g.gif" /></figure><p>Let’s just see some of these below.</p><h4>Debugging info</h4><p>WebViews and some controllers have debugging info enabled by default when your flutter app is running in debug mode (based on the kDebugMode flutter constant value).</p><p>For example, while an InAppWebView or HeadlessInAppWebView is running, you will see debugging info in your IDE log console with details of the various fired WebView events.</p><p>Through the PlatformInAppWebViewController.debugLoggingSettings static property, you can change the DebugLoggingSettings values.</p><p>If you want to disable WebView debugging info, simply set the PlatformInAppWebViewController.debugLoggingSettings.enabled to false.</p><p>Check more on <a href="https://inappwebview.dev/docs/debugging-webviews/">Debugging WebViews</a>.</p><h4>Proxy Controller for Android</h4><p>ProxyController represents the proxy settings that govern network requests made by WebView. It&#39;s available only on Android!</p><p>This API may be used to explicitly specify the proxy rules that govern WebView-initiated network requests.</p><p>Check more on <a href="https://inappwebview.dev/docs/webview/proxy-controller">Proxy Controller</a>.</p><h4>Print Job Controller</h4><p>PrintJobController represents the controller used by the WebView to manage print jobs.</p><p>A PrintJobController is returned by the InAppWebViewController.printCurrentPage(PrintJobSettings? settings) method or as an argument when the onPrintRequest event is fired.</p><p>To obtain the instance when using the printCurrentPage method, set PrintJobSettings.handledByClient to true.</p><p>With PrintJobSettings you can set various print settings (some are platform-specific!), such as the color and orientation print mode.</p><p>Here is an example:</p><pre>final jobSettings = PrintJobSettings(<br>  handledByClient: true,<br>  jobName: (await webViewController.getTitle() ?? ‘’) +<br>    “ — PDF Document example”,<br>  colorMode: PrintJobColorMode.MONOCHROME,<br>  outputType: PrintJobOutputType.GRAYSCALE,<br>  orientation: PrintJobOrientation.LANDSCAPE,<br>  numberOfPages: 1);</pre><pre>final printJobController = await webViewController<br>  .printCurrentPage(settings: jobSettings);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*CipP8UDSvg1L_QDusvZDeA.gif" /><figcaption>iOS Print Job Controller example.</figcaption></figure><p>Check more on <a href="https://inappwebview.dev/docs/webview/print-job-controller">Print Job Controller</a>.</p><h4>Find Interaction Controller</h4><p>FindInteractionController represents the controller used by the WebView to add text-finding capabilities, such as the &quot;Find on page&quot; feature.</p><p>Before it, you could use the InAppWebViewController.findAllAsync and InAppWebViewController.findNext methods and listen for the WebView.onFindResultReceived event, that are now deprecated!</p><p>With this controller, now you have more fine-grain control over the search feature. On iOS, if theInAppWebViewSettings.isFindInteractionEnabled setting is true , it will use the web view’s built-in find interaction native UI!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*d9bvZ-p-gVe45srOv3SlhA.gif" /><figcaption>iOS example with and without native UI.</figcaption></figure><p>Check more on <a href="https://inappwebview.dev/docs/webview/find-interaction-controller/">Find Interaction Controller</a>.</p><h4>WebView onPermissionRequest event on iOS 15.0+</h4><p>The onPermissionRequest event is now supported also on iOS 15.0+, which you can use, as you already do on Android, to grant or deny permission about the camera, microphone, and device orientation/motion.</p><p>Example:</p><pre>onPermissionRequest: (controller, request) async {<br>  return PermissionResponse(<br>      resources: request.resources,<br>      action: PermissionResponseAction.<em>GRANT</em>);<br>},</pre><h3>Conclusion</h3><p>That’s all for today!</p><p>If this project helps you in any way, please consider <a href="https://inappwebview.dev/donate">making a donation</a>!</p><p>Are you using this plugin? Submit your app through the <a href="https://inappwebview.dev/submit-app/">Submit App</a> page and follow the instructions.<br>Check the <a href="https://inappwebview.dev/showcase/">Showcase</a> page to see who is already using it!</p><p>This project follows the <a href="https://github.com/all-contributors/all-contributors">all-contributors</a> specification (<a href="https://github.com/pichillilorenzo/flutter_inappwebview#contributors-">contributors</a>). I want to thank all the people that are supporting the project in any way. Thanks a lot to all of you! 💙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0bcef5ca3cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter WebView JavaScript Communication — InAppWebView 5]]></title>
            <link>https://medium.com/flutter-community/flutter-webview-javascript-communication-inappwebview-5-403088610949?source=rss-11e6aac5f656------2</link>
            <guid isPermaLink="false">https://medium.com/p/403088610949</guid>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[flutter-webview]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-plugin]]></category>
            <category><![CDATA[in-app-browsers]]></category>
            <dc:creator><![CDATA[Lorenzo Pichilli]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 20:32:40 GMT</pubDate>
            <atom:updated>2021-04-19T20:32:40.236Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter WebView JavaScript Communication — InAppWebView 5</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3O9GGlwE7iwRvSHLarvuDg.png" /><figcaption>Flutter InAppWebView JavaScript 2-way Communication.</figcaption></figure><p>In this in-depth tutorial, I’m going to explain how you can communicate from Dart (Flutter WebView) to JavaScript and vice-versa using my <a href="https://github.com/pichillilorenzo/flutter_inappwebview">flutter_inappwebview</a> plugin (at the time of this writing, the latest release is 5.3.2).</p><p>There are 3 main ways to enable this 2-way communication:</p><ul><li><strong>JavaScript Handlers</strong>;</li><li><strong>Web Message Channels</strong>;</li><li><strong>Web Message Listeners</strong>.</li></ul><h3>JavaScript Handlers</h3><p>The <strong>JavaScript Handler</strong> concept is similar to the native <a href="https://developer.android.com/reference/android/webkit/JavascriptInterface">Android WebView JavaScript Interface</a> and the <a href="https://developer.apple.com/documentation/webkit/wkscriptmessagehandler">iOS WKWebView JavaScript Message Handler</a> ones, but it offers a cross-platform way of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*lQwcMHwf78brG9Yg.gif" /><figcaption>Android and iOS together toward the cross-platform way.</figcaption></figure><p>For each JavaScript Handler, you can define its name and a callback that will be invoked when it is called by the JavaScript side. Also, the callback can return data to the JavaScript side as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> type.</p><p>To add a JavaScript Handler, you can use the InAppWebViewController.addJavaScriptHandler method. If you need to manage JavaScript Handlers as soon as the web page is loaded, this method should be called when the InAppWebView is created, like this:</p><pre>onWebViewCreated: (controller) {<br>  <em>// register a JavaScript handler with name &quot;myHandlerName&quot;</em><br>  controller.addJavaScriptHandler(handlerName: &#39;myHandlerName&#39;, callback: (args) {<br>    <em>// print arguments coming from the JavaScript side!</em><br>    print(args);</pre><pre>    <em>// return data to the JavaScript side!</em><br>    return {<br>      &#39;bar&#39;: &#39;bar_value&#39;, &#39;baz&#39;: &#39;baz_value&#39;<br>    };<br>  });<br>},</pre><p>The return type of the callback will be automatically JSON encoded using thejsonEncode function of the dart:convert library. So, you can send back to JavaScript all JSON encodable types.</p><p>Instead, on the JavaScript side, to execute the callback handler and send data to Flutter, you need to use the window.flutter_inappwebview.callHandler(handlerName, ...args) method, where handlerName is a string that represents the handler name that you are calling and args are optional arguments that you can send to the Flutter side.</p><p><strong>Note</strong> that if you want a different name instead of window.flutter_inappwebview, you can simply wrap it inside another JavaScript function or object. For example: window.myCustomObj = { callHandler: window.flutter_inappwebview.callHandler }; and, then, you can use window.myCustomObj.callHandler in the same way.</p><p>Also, you can wrap a whole specific handler this way:</p><pre>const myHandlerName = function(...args) {<br>  return window.flutter_inappwebview.callHandler(&#39;myHandlerName&#39;, ...args);<br>};<br><em>// and then use it</em><br>myHandlerName();</pre><p>In order to call window.flutter_inappwebview.callHandler properly inside a JavaScript file or a &lt;script&gt; HTML tag, you need to wait and listen to the flutterInAppWebViewPlatformReady JavaScript event. This event will be dispatched as soon as the platform is ready to handle the callHandler method. You can also use a global flag variable that is set when the flutterInAppWebViewPlatformReady event is dispatch and use it before calling the window.flutter_inappwebview.callHandler method.</p><p>Here is a JavaScript example code:</p><pre><em>// execute inside the &quot;flutterInAppWebViewPlatformReady&quot; event listener</em><br>window.addEventListener(&quot;flutterInAppWebViewPlatformReady&quot;, function(event) {<br>  const args = [1, true, [&#39;bar&#39;, 5], {foo: &#39;baz&#39;}];<br>  window.flutter_inappwebview.callHandler(&#39;myHandlerName&#39;, ...args);<br>});</pre><pre><em>// or using a global flag variable</em><br>var isFlutterInAppWebViewReady = false;<br>window.addEventListener(&quot;flutterInAppWebViewPlatformReady&quot;, function(event) {<br>  isFlutterInAppWebViewReady = true;<br>});<br><em>// then, somewhere in your code</em><br>if (isFlutterInAppWebViewReady) {<br>  const args = [1, true, [&#39;bar&#39;, 5], {foo: &#39;baz&#39;}];<br>  window.flutter_inappwebview.callHandler(&#39;myHandlerName&#39;, ...args);<br>}</pre><p>Instead, if you are evaluating JavaScript code from the Dart (Flutter) side, you can call window.flutter_inappwebview.callHandler directly on the onLoadStop event (or after that) without listening to the flutterInAppWebViewPlatformReady JavaScript event because, at that time, it will be already fired. For example:</p><pre>onLoadStop: (controller, url) async {<br>  await controller.evaluateJavascript(source: &quot;&quot;&quot;<br>    const args = [1, true, [&#39;bar&#39;, 5], {foo: &#39;baz&#39;}];<br>    window.flutter_inappwebview.callHandler(&#39;myHandlerName&#39;, ...args);<br>  &quot;&quot;&quot;);<br>},</pre><p>Here is an example of communication:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1404ecda2ef92098fd84bfa4fce28860/href">https://medium.com/media/1404ecda2ef92098fd84bfa4fce28860/href</a></iframe><p>Another way to communicate with JavaScript is to evaluate some JavaScript code using, for example, the InAppWebViewController.evaluateJavascript method.</p><p>You could set up a message event listener (used with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage">postMessage</a>) or a custom event listener (see <a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent">CustomEvent</a> for details), such as:</p><pre><em>// message event listener</em><br>window.addEventListener(&quot;message&quot;, (event) =&gt; {<br>  console.log(event.data);<br>}, false);</pre><pre><em>// or custom event listener</em><br>window.addEventListener(&quot;myCustomEvent&quot;, (event) =&gt; {<br>  console.log(event.detail);<br>}, false);</pre><p>And then, you can dispatch the custom JavaScript event whenever and wherever you want:</p><pre><em>// using postMessage method</em><br>window.postMessage({foo: 1, bar: false});</pre><pre><em>// or dispatching a custom event</em><br>const event = new CustomEvent(&quot;myCustomEvent&quot;, {<br>    detail: {foo: 1, bar: false}<br>});<br>window.dispatchEvent(event);</pre><p>So, you can set up these event listeners at runtime using the InAppWebViewController.evaluateJavascript method or inside the web app itself and dispatch these events using the same method, for example:</p><pre>onLoadStop: (controller, url) async {<br>  await controller.evaluateJavascript(source: &quot;&quot;&quot;<br>    window.addEventListener(&quot;myCustomEvent&quot;, (event) =&gt; {<br>      console.log(JSON.stringify(event.detail));<br>    }, false);<br>  &quot;&quot;&quot;);</pre><pre>  await Future.delayed(Duration(seconds: 5));</pre><pre>  controller.evaluateJavascript(source: &quot;&quot;&quot;<br>    const event = new CustomEvent(&quot;myCustomEvent&quot;, {<br>      detail: {foo: 1, bar: false}<br>    });<br>    window.dispatchEvent(event);<br>  &quot;&quot;&quot;);<br>},<br>onConsoleMessage: (controller, consoleMessage) {<br>  print(consoleMessage);<br>  <em>// it will print: {message: {&quot;foo&quot;:1,&quot;bar&quot;:false}, messageLevel: 1}</em><br>},</pre><h3>Web Message Channels</h3><p>Another way is to use <strong>Web Message Channels</strong>, which are the representation of the <a href="https://html.spec.whatwg.org/multipage/web-messaging.html#message-channels">HTML5 message channels</a>. See <a href="https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API">Channel Messaging API</a> for more details.</p><p>It allows you to create a new message channel and send data through it via its two WebMessagePort properties:</p><ul><li>port1, that is the first WebMessagePort;</li><li>port2, that is the second WebMessagePort.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Q1pNSOrnMw6TS8Dq.gif" /><figcaption>It’s all about connection. Yep.</figcaption></figure><p>To create a Web Message Channel, you need to use the InAppWebViewController.createWebMessageChannel method (the official native Android WebView API can be found <a href="https://developer.android.com/reference/android/webkit/WebView#createWebMessageChannel()">here</a>). This method should be called when the page is loaded, for example, when the onLoadStop event is fired, otherwise, the WebMessageChannel won’t work.</p><p><strong>Note for Android</strong>: This method should only be called if AndroidWebViewFeature.isFeatureSupported returns true for AndroidWebViewFeature.CREATE_WEB_MESSAGE_CHANNEL.</p><p>Here is an example of it:</p><pre>onLoadStop: (controller, url) async {<br>    if (!Platform.isAndroid || await AndroidWebViewFeature.isFeatureSupported(AndroidWebViewFeature.CREATE_WEB_MESSAGE_CHANNEL)) {<br>        var webMessageChannel = await controller.createWebMessageChannel();<br>        var port1 = webMessageChannel!.port1;<br>        var port2 = webMessageChannel.port2;<br>    }<br>},</pre><p>The Dart side that created the channel uses port1, and the JavaScript side at the other end of the port uses port2 — you send a message to port2, and transfer the port over to the other browsing context using the InAppWebViewController.postWebMessage method along with the message to send, and the object to transfer ownership of, in this case, the port itself.</p><p>When these transferable port objects are transferred, they are “neutered” on the previous context — the one they previously belonged to. For instance, a port, when is sent to JavaScript, cannot be used to send or receive messages at the Dart side anymore. Also, different from HTML5 Spec, a port cannot be transferred if one of these has ever happened:</p><ul><li>a message callback was set;</li><li>a message was posted on it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*uXk3KNFlXmFLvJnQ.gif" /></figure><p>I know what you are thinking: “<em>blah blah blah.. come on, let me see the code!</em>”. Don’t worry, we are almost there!</p><p>A transferred port cannot be closed by the application, since the ownership is also transferred.</p><p>To listen for the messages on a port from the Dart side, you need to set the WebMessageCallback using the WebMessagePort.setWebMessageCallback method. You could then respond by sending a message back to the original document using the WebMessagePort.postMessage method.</p><p>When you want to stop sending messages down the channel, you can invoke WebMessagePort.close to close the ports. A closed port cannot be transferred or cannot be reopened to send messages.</p><p>To be able to listen to messages from the JavaScript side, you need to first “capture” the port coming from the Dart side.</p><p>Here is finally the expected example of communication for you:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d53d75b5ebe9f32964ea7858dc873f85/href">https://medium.com/media/d53d75b5ebe9f32964ea7858dc873f85/href</a></iframe><h3>Web Message Listeners</h3><p><strong>Web Message Listeners</strong> are similar to the JavaScript Handlers and Web Message Channels. It allows injecting a JavaScript object into each frame that the WebMessageListener will listen on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*bzVcKVCFdgFQC5Aw.gif" /><figcaption>Example of a Web Message Listener.</figcaption></figure><p>To add a Web Message Listener, you need to use the InAppWebViewController.addWebMessageListener method. This method should be called before the webpage that uses it is loaded, for example when the onWebViewCreated event is fired.</p><p><strong>Note for Android</strong>: Similar to the Web Message Channel, this method should only be called if AndroidWebViewFeature.isFeatureSupported returns true for AndroidWebViewFeature.WEB_MESSAGE_LISTENER.</p><pre>child: InAppWebView(<br>  onWebViewCreated: (controller) async {<br>   <em>// add first all of your web message listeners</em><br>   if (!Platform.isAndroid || await AndroidWebViewFeature.isFeatureSupported(AndroidWebViewFeature.WEB_MESSAGE_LISTENER)) {<br>     await controller.addWebMessageListener(WebMessageListener(<br>       jsObjectName: &quot;myObject&quot;,<br>       allowedOriginRules: Set.from([&quot;https://*.example.com&quot;]),<br>       onPostMessage: (message, sourceOrigin, isMainFrame, replyProxy) {<br>         replyProxy.postMessage(&quot;Got it!&quot;);<br>       },<br>     ));<br>   }<br>   <br>   <em>// then load your URL</em><br>   await controller.loadUrl(urlRequest: URLRequest(url: Uri.parse(&quot;https://www.example.com&quot;)));<br>  },<br>),</pre><p>The injected JavaScript object will be named WebMessageListener.jsObjectName in the global scope. This will inject the JavaScript object in any frame whose origin matches WebMessageListener.allowedOriginRules for every navigation after this call, and the JavaScript object will be available immediately when the page begins to load.</p><p>Each WebMessageListener.allowedOriginRules entry must follow the format SCHEME &quot;://&quot; [ HOSTNAME_PATTERN [ &quot;:&quot; PORT ] ], each part is explained in <a href="https://developer.android.com/reference/androidx/webkit/WebViewCompat#addWebMessageListener(android.webkit.WebView,%20java.lang.String,%20java.util.Set%3Cjava.lang.String%3E,%20androidx.webkit.WebViewCompat.WebMessageListener)">this table</a>.</p><p>The HTTPS scheme is strongly recommended for security because the JavaScript object will be injected when the frame’s origin matches any one of the allowed origins. Allowing HTTP origins exposes the injected object to any potential network-based attackers.</p><p>If a wildcard “*” is provided, it will inject the JavaScript object into all frames. A wildcard should only be used if the app wants <strong>any</strong> third-party web page to be able to use the injected object. When using a wildcard, the app must treat received messages as untrustworthy and validate any data carefully.</p><p>You can call this method multiple times to inject multiple JavaScript objects!</p><p>Each injected JavaScript object will have the following methods/properties:</p><ul><li>postMessage(message[, MessagePorts]) on Android and postMessage(message) on iOS, where the message is a String;</li><li>onmessage: To receive messages posted from the Flutter App side, assign a function to this property. This function should accept a single &quot;event&quot; argument (onmessage = function(event) { ... }). &quot;event&quot; has a &quot;data&quot; property, which is the message string from the Flutter App side;</li><li>addEventListener(type, listener): To be compatible with DOM EventTarget&#39;s addEventListener, it accepts type and listener parameters where type can be only &quot;message&quot; type and listener can only be a JavaScript function that has the same functionality of the onmessage property function;</li><li>removeEventListener(type, listener): To be compatible with DOM EventTarget&#39;s removeEventListener, it accepts type and listener parameters. It is used to remove an event listener added using the addEventListener method.</li></ul><p>The communication must be initialized on the JavaScript side first, posting a message, so the Flutter App will have a JavaScriptReplyProxy object to respond.</p><p>JavaScript side:</p><pre><em>// Web page (in JavaScript)</em><br>myObject.onmessage = function(event) {<br>  <em>// prints &quot;Got it!&quot; when we receive the app&#39;s response.</em><br>  console.log(event.data);<br>}<br>myObject.postMessage(&quot;I&#39;m ready!&quot;);</pre><p>Flutter side:</p><pre><em>// Flutter App</em><br>child: InAppWebView(<br>  onWebViewCreated: (controller) async {<br>   if (!Platform.isAndroid || await AndroidWebViewFeature.isFeatureSupported(AndroidWebViewFeature.WEB_MESSAGE_LISTENER)) {<br>     await controller.addWebMessageListener(WebMessageListener(<br>       jsObjectName: &quot;myObject&quot;,<br>       onPostMessage: (message, sourceOrigin, isMainFrame, replyProxy) {<br>         <em>// do something about message, sourceOrigin and isMainFrame.</em><br>         replyProxy.postMessage(&quot;Got it!&quot;);<br>       },<br>     ));<br>   }<br>   await controller.loadUrl(urlRequest: URLRequest(url: Uri.parse(&quot;https://www.example.com&quot;)));<br>  },<br>),</pre><h3>Conclusion</h3><p>Now, after this tutorial, you can start experimenting with the different 2-way communication methods and choose which one is best for you and fits your needs.</p><p>That’s all for today!</p><p>As always, thanks to all people that are supporting this project! 💙</p><p><a href="https://www.twitter.com/FlutterComm">JavaScript is not available.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=403088610949" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/flutter-webview-javascript-communication-inappwebview-5-403088610949">Flutter WebView JavaScript Communication — InAppWebView 5</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s new in InAppWebView 5? Null-safety, new features, bug fixes]]></title>
            <link>https://medium.com/flutter-community/whats-new-in-inappwebview-5-null-safety-new-features-bug-fixes-11c9e2cadab2?source=rss-11e6aac5f656------2</link>
            <guid isPermaLink="false">https://medium.com/p/11c9e2cadab2</guid>
            <category><![CDATA[android-webview]]></category>
            <category><![CDATA[in-app-browsers]]></category>
            <category><![CDATA[flutter-webview]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[webview]]></category>
            <dc:creator><![CDATA[Lorenzo Pichilli]]></dc:creator>
            <pubDate>Tue, 23 Mar 2021 23:45:29 GMT</pubDate>
            <atom:updated>2021-03-24T08:28:22.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rqvmckkxe7Qn7LFbq4y-Gw.png" /><figcaption>Flutter InAppWebView.</figcaption></figure><p>Finally, after a lot of work, the new version 5 of the <a href="https://github.com/pichillilorenzo/flutter_inappwebview">flutter_inappwebview</a> plugin is out (at the time of this writing, the latest release is <a href="https://pub.dev/packages/flutter_inappwebview">5.2.0</a>)!</p><p>So, what’s new? What changed?</p><p>Well.. a lot!</p><h4>Null-safety support</h4><p>InAppWebView 5 comes with Dart <strong>null-safety support</strong>! What does this mean? We know that the null-safety feature has been released recently in the stable version of Dart (it requires Dart SDK &gt;=2.12.0-0 &lt;3.0.0), so, to use this plugin, you need to upgrade Flutter to the new version 2 or switching channel, for example, to the <strong>dev</strong> channel: flutter channel dev and, then, flutter upgrade (see <a href="https://flutter.dev/docs/development/tools/sdk/upgrading#switching-flutter-channels">Switching Flutter channels</a>).</p><h4>Android Hybrid Composition support</h4><p>Use the new WebView Android-specific option useHybridComposition: true to enable Hybrid Composition.<br>This will <strong>improve</strong> a lot the <strong>performance</strong> of the WebView on Android, and, also, will resolve all the problems related to the <strong>keyboard</strong>!<br>Note that this option requires Flutter v1.20+ and should only be used on Android 10+ for release apps, as animations will drop frames on &lt; Android 10 (see <a href="https://github.com/flutter/flutter/wiki/Hybrid-Composition#performance">Hybrid-Composition#performance</a>).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fq1MeAPDDMb43K%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcat-laugh-funny-q1MeAPDDMb43K&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fq1MeAPDDMb43K%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="272" frameborder="0" scrolling="no"><a href="https://medium.com/media/07ffb9978d17e38e5fb8b63db4d12033/href">https://medium.com/media/07ffb9978d17e38e5fb8b63db4d12033/href</a></iframe><h4>No more URL as a String = fewer problems</h4><p>All class properties that represent an URL as a String now have been converted to Uri type. Why this change? URL represented by a simple String could be problematic in some cases, for example when you have spaces or special chars inside it not encoded correctly.<br>Using Uri.parse() and converting a String in a Uri will solve you a lot of problems with URLs!</p><p>Also, there is the new class URLRequest that represents, well, a URL load request that uses Uri as the type of the url property.<br>This class is used when you want to use the loadUrl method or in the new WebView property initialUrlRequest (that replaces the old initialUrl and initialHeaders properties). A simple usage example is:</p><pre>child: InAppWebView(<br>  initialUrlRequest: URLRequest(<br>      url: Uri.<em>parse</em>(&quot;https://flutter.dev/&quot;)<br>  ),<br>),</pre><p>Furthermore, with URLRequest , you can make an initial POST request, such as:</p><pre>child: InAppWebView(<br>  initialUrlRequest: URLRequest(<br>    url: Uri.<em>parse</em>(&quot;https://example.com&quot;),<br>    method: &#39;POST&#39;,<br>    body: Uint8List.fromList(utf8.encode(&quot;name=FooBar&quot;)),<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;<br>    }<br>  ),<br>),</pre><p>Unfortunately, on Android, POST requests will ignore the headers property because there isn’t any native API to load POST requests with headers such as loadUrl . That’s because the native method <a href="https://developer.android.com/reference/android/webkit/WebView#postUrl(java.lang.String,%20byte[])">android.webkit.WebView.postUrl</a> is the only one that can send this type of request.</p><h4>Limited Cookies support on iOS &lt; 11.0</h4><p>Because <a href="https://developer.apple.com/documentation/webkit/wkhttpcookiestore">WKHTTPCookieStore</a> is available only on iOS ≥ 11.0, it has been added limited support for iOS &lt; 11.0 through JavaScript, so, you cannot get, create or change HttpOnly cookies. Also, for session-only cookies, you need to use the new iosBelow11WebViewController argument (if available for that Cookie Manager method you want to use).</p><h4>User Scripts</h4><p>What is an UserScript ? We can say that the UserScript class is the equivalent of the <a href="https://developer.apple.com/documentation/webkit/wkuserscript">WKUserScript</a> iOS native class.<br>Why should I use it when I can just use evaluateJavascript method to inject my JavaScript code? Well yes, but nope! UserScript gives you the possibility to inject JavaScript <strong>before</strong> other resources are loaded, setting the injectionTime property, for example, to UserScriptInjectionTime.AT_DOCUMENT_START (that is the equivalent of the <a href="https://developer.apple.com/documentation/webkit/wkuserscriptinjectiontime/atdocumentstart">WKUserScriptInjectionTime.atDocumentStart</a> iOS native property).</p><p>However, I should make a precision here for Android. What I said is guaranteed on iOS, but not on Android (do you know that iOS != Android? 🤷‍♂️)!<br>That’s because the corresponding native class/feature doesn’t exist on the Android side, so InAppWebView tries to inject all the user scripts as soon as possible. You can think of that as something like this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYq5gG91kM4Yko%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcat-fight-Yq5gG91kM4Yko&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2FYq5gG91kM4Yko%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="332" frameborder="0" scrolling="no"><a href="https://medium.com/media/f30796709845dcb1ad703a0cb06fadde/href">https://medium.com/media/f30796709845dcb1ad703a0cb06fadde/href</a></iframe><p>To manage UserScripts you can use the corresponding methods, such as addUserScript, removeUserScript, etc.</p><h4>Content Worlds</h4><p>Starting from iOS 14.0+, WebKit introduces the concept of <a href="https://developer.apple.com/documentation/webkit/wkcontentworld">WKContentWorld</a>s, which is an object that defines a scope of execution for JavaScript code, and which you use to prevent conflicts between different scripts.<br>This concept has been introduced also into the flutter_inappwebview plugin with the new, you guessed it, ContentWorld class.</p><p>But, as I said before, iOS != Android and, on Android, this concept doesn’t exist natively. So, it has been implemented with the usage of &lt;iframe&gt; HTML elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PlNZHkjEiP4h53ruylI9uQ.gif" /><figcaption>As a famous Italian said once: “First reaction, SHOCK!”.</figcaption></figure><p>You may ask why I didn’t use something like the <a href="https://github.com/LiquidPlayer/LiquidCore">LiquidCore</a> library or something similar to the <a href="https://developer.apple.com/documentation/javascriptcore">JavaScriptCore</a> iOS framework to implement it.<br>The problem with using these libraries/framework is that you can’t access the window or document JavaScript objects of the current webpage, of course.<br>Instead, with WKContentWorld, you can access these objects and, so, you can interact with the webpage itself.<br>Using iframes on Android gives you the ability to create a new JavaScript context without conflicting with the main JavaScript context of the webpage (you can have, for example, 2 variables with the same name, because they exist in 2 different contexts/content worlds) and implement this sort of Content World such as on iOS. So, this plugin will create and append an &lt;iframe&gt; with id attribute equals to flutter_inappwebview_[Content World Name HERE] to the webpage’s content that contains only the inline scripts in order to define a new scope of execution for JavaScript code.</p><p>Obviously, this comes with some limitations/disadvantages:</p><ul><li>for any ContentWorld, except ContentWorld.PAGE (that is the webpage itself), if you need to access the window or document global Object, you need to use window.top and window.top.document because the code runs inside an iframe;</li><li>the execution of the inline scripts could be blocked by the Content-Security-Policy header.</li></ul><p>A simple example:</p><pre>child: InAppWebView(<br>  initialUrlRequest: URLRequest(<br>    url: Uri.<em>parse</em>(&quot;https://flutter.dev&quot;),<br>  ),<br>  onLoadStop: (controller, url) async {<br>    await controller.evaluateJavascript(source: &quot;var foo = 49;&quot;);<br>    await controller.evaluateJavascript(source: &quot;var bar = 19;&quot;,<br>        contentWorld: ContentWorld.<em>PAGE</em>);<br>    print(await controller.evaluateJavascript(source: &quot;foo + bar;&quot;));<br><br>    print(await controller.evaluateJavascript(source: &quot;bar;&quot;,<br>        contentWorld: ContentWorld.<em>DEFAULT_CLIENT</em>));<br>    await controller.evaluateJavascript(source: &quot;var bar = 2;&quot;,<br>        contentWorld: ContentWorld.<em>DEFAULT_CLIENT</em>);<br>    print(await controller.evaluateJavascript(source: &quot;bar;&quot;,<br>        contentWorld: ContentWorld.<em>DEFAULT_CLIENT</em>));<br><br>    if (Platform.<em>isIOS</em>) {<br>      await controller.evaluateJavascript(<br>          source: &quot;document.body.innerHTML = &#39;LOL&#39;;&quot;,<br>          contentWorld: ContentWorld.world(name: &quot;MyWorld&quot;));<br>    } else {<br>      await controller.evaluateJavascript(<br>          source: &quot;window.top.document.body.innerHTML = &#39;LOL&#39;;&quot;,<br>          contentWorld: ContentWorld.world(name: &quot;MyWorld&quot;));<br>    }<br>  },<br>  onConsoleMessage: (controller, consoleMessage) {<br>    print(consoleMessage);<br>  },<br>),</pre><p>The proof of this example is left to the reader.</p><h4>Apple Pay API</h4><p>A new WebView option has been added for iOS 13.0+ to enable the JavaScript Apple Pay API: applePayAPIEnabled. As written in the official <a href="https://developer.apple.com/documentation/safari-release-notes/safari-13-release-notes#Payment-Request-API">Safari 13 Release Notes</a>, it won’t work if any script injection APIs are used (such as evaluateJavascript or UserScript).<br>So, when this attribute is true, all the methods, options, and events implemented using JavaScript on iOS won’t be called or won’t do anything and the result will always be null, but, hey, you will get paid from your users 🤑 (that’s good, no?).</p><p>Check the official flutter_inappwebview documentation for the full list of API affected by this!</p><h4>Evaluate Async JavaScript code</h4><p>Starting from iOS 14.0+, WebKit added the new <a href="https://developer.apple.com/documentation/webkit/wkwebview/3656441-callasyncjavascript">callAsyncJavaScript</a> method, which allows the execution of the source code as an asynchronous JavaScript function (see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">MDN — async function</a>). This method has been implemented on both Android and iOS platforms.</p><p>On iOS, you can use this function starting from iOS 10.3+ because, as stated here: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#browser_compatibility">async function Browser Compatibility</a>, async functions should be already supported from that version. So, for iOS versions inside the range [10.3, 14.0), it has been implemented using the evaluateJavascript method and using a Map that contains an identifier and a callback that will be called at the end of the async function execution with the returned result. On Android, it has been implemented the same way!</p><p>The return type is not the same as the evaluateJavascript method, but a CallAsyncJavaScriptResult instance, where the value property contains the success value (if any) and the error property contains a String representing the failure value (if any).</p><p>Here is an example:</p><pre>child: InAppWebView(<br>  initialUrlRequest: URLRequest(<br>    url: Uri.<em>parse</em>(&quot;https://flutter.dev&quot;),<br>  ),<br>  onLoadStop: (controller, url) async {<br>    final String functionBody = &quot;&quot;&quot;<br>        var p = new Promise(function (resolve, reject) {<br>           window.setTimeout(function() {<br>             if (x &gt;= 0) {<br>               resolve(x);<br>             } else {<br>               reject(y);<br>             }<br>           }, 1000);<br>        });<br>        await p;<br>        return p;<br>      &quot;&quot;&quot;;<br><br>    var result = await controller.callAsyncJavaScript(<br>        functionBody: functionBody,<br>        arguments: {&#39;x&#39;: 49, &#39;y&#39;: &#39;error message&#39;});<br>    print(result);<br><br>    result = await controller.callAsyncJavaScript(<br>        functionBody: functionBody,<br>        arguments: {&#39;x&#39;: -49, &#39;y&#39;: &#39;error message&#39;});<br>    print(result);<br>  },<br>),</pre><p>that will print {value: 49, error: null} and {value: null, error: &quot;error message&quot;} respectively.</p><h4>Service Worker API</h4><p>On Android, the AndroidServiceWorkerController and AndroidServiceWorkerClient classes can be used to intercept requests. Before using these classes or their methods, you should check if the service worker features you want to use are supported or not, for example:</p><pre>Future main() async {<br>  WidgetsFlutterBinding.ensureInitialized();</pre><pre>  if (Platform.isAndroid) {<br>    await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);</pre><pre>    var swAvailable = await AndroidWebViewFeature.isFeatureSupported(AndroidWebViewFeature.SERVICE_WORKER_BASIC_USAGE);<br>    var swInterceptAvailable = await AndroidWebViewFeature.isFeatureSupported(AndroidWebViewFeature.SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST);</pre><pre>    if (swAvailable &amp;&amp; swInterceptAvailable) {<br>      AndroidServiceWorkerController serviceWorkerController = AndroidServiceWorkerController.instance();</pre><pre>      serviceWorkerController.serviceWorkerClient = AndroidServiceWorkerClient(<br>        shouldInterceptRequest: (request) async {<br>          print(request);<br>          return null;<br>        },<br>      );<br>    }<br>  }</pre><pre>  runApp(MyApp());<br>}</pre><p>Instead, on iOS, the JavaScript Service Worker API is available starting from iOS 14.0+.</p><p>To enable this JavaScript API on iOS there are only 2 ways:</p><ul><li>using “App-Bound Domains”</li><li>your App proposes itself as a possible “Default Browser” such as iOS Safari or Google Chrome</li></ul><p><strong>App-Bound Domains</strong>: read the <a href="https://webkit.org/blog/10882/app-bound-domains/">WebKit — App-Bound Domains</a> article for details. You can specify up to 10 “app-bound” domains using the new Info.plist key WKAppBoundDomains, for example:</p><pre>&lt;dict&gt;<br>&lt;key&gt;WKAppBoundDomains&lt;/key&gt;<br>&lt;array&gt;<br>    &lt;string&gt;flutter.dev&lt;/string&gt;<br>    &lt;string&gt;github.com&lt;/string&gt;<br>&lt;/array&gt;<br>&lt;/dict&gt;</pre><p>After that, you need to set to true the limitsNavigationsToAppBoundDomains iOS-specific WebView option, for example:</p><pre>InAppWebViewGroupOptions(<br>  ios: IOSInAppWebViewOptions(<br>    limitsNavigationsToAppBoundDomains: true<br>  )<br>)</pre><p><strong>iOS Default Browser</strong>: read the <a href="https://developer.apple.com/documentation/xcode/allowing_apps_and_websites_to_link_to_your_content/preparing_your_app_to_be_the_default_browser_or_email_client">Preparing Your App to be the Default Browser or Email Client</a> article for details.</p><h4>Web Message Channels and Web Message Listeners</h4><p>There are two new ways to communicate with JavaScript other than JavaScript Handlers:</p><ul><li><strong>Web Message Channels</strong>: they are the representation of the <a href="https://html.spec.whatwg.org/multipage/web-messaging.html#message-channels">HTML5 message channels</a>. See <a href="https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API">Channel Messaging API</a> for more details. To create a Web Message Channel, you need to use the InAppWebViewController.createWebMessageChannel method. This method should be called when the page is loaded, for example, when the WebView.onLoadStop event is fired.</li><li><strong>Web Message Listeners</strong>: It allows to inject a JavaScript object into each frame that the WebMessageListener will listen on. To add a Web Message Listener, you need to use the InAppWebViewController.addWebMessageListener method. This method should be called before the webpage that uses it is loaded, for example when the WebView.onWebViewCreated event is fired.</li></ul><h4>Official WebSite</h4><p>The official website of this plugin has been published on <a href="https://inappwebview.dev/">inappwebview.dev</a>!<br>All the initial setup and configuration written on the README.md of the repository have been moved to the new <a href="https://inappwebview.dev/docs/">Docs page</a>!</p><p>Also, it contains a <a href="https://inappwebview.dev/showcase/">Showcase</a> section with an open list of apps built with Flutter and Flutter InAppWebView. At this time, because the website is new, there is only one App, that is the <a href="https://inappwebview.dev/flutter-app/flutter-browser/">Flutter Browser App</a>.</p><p>Are you using this plugin? Submit your app through the <a href="https://inappwebview.dev/submit-app/">Submit App</a> page and follow the instructions!</p><h4>Conclusion</h4><p>Check the <a href="https://github.com/pichillilorenzo/flutter_inappwebview/blob/master/CHANGELOG.md">CHANGELOG.md</a> file to see the full list of what is changed and what is fixed!</p><p>That’s all for today!</p><p>I want to thank all the people that are supporting the project in any way! Thanks a lot to all of you! 💙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11c9e2cadab2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/whats-new-in-inappwebview-5-null-safety-new-features-bug-fixes-11c9e2cadab2">What’s new in InAppWebView 5? Null-safety, new features, bug fixes</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Full-Featured Browser using WebViews in Flutter]]></title>
            <link>https://medium.com/flutter-community/creating-a-full-featured-browser-using-webviews-in-flutter-9c8f2923c574?source=rss-11e6aac5f656------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c8f2923c574</guid>
            <category><![CDATA[in-app-browsers]]></category>
            <category><![CDATA[flutter-webview]]></category>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[browsers]]></category>
            <dc:creator><![CDATA[Lorenzo Pichilli]]></dc:creator>
            <pubDate>Fri, 17 Jul 2020 10:01:02 GMT</pubDate>
            <atom:updated>2020-07-21T14:54:36.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8wFh-pEuwyAGa1IaKb-lEw.png" /></figure><p>In this article, I’m going to show how to create a full-featured mobile Browser App such as the <a href="https://play.google.com/store/apps/details?id=com.android.chrome&amp;hl=en">Google Chrome</a> mobile browser using the features offered by the <a href="https://github.com/pichillilorenzo/flutter_inappwebview">flutter_inappwebview</a> plugin.</p><p><em>Check out the previous article that introduces the </em><strong><em>flutter_inappwebview</em></strong><em> plugin here: </em><a href="https://medium.com/flutter-community/inappwebview-the-real-power-of-webviews-in-flutter-c6d52374209d"><strong><em>InAppWebView: The Real Power of WebViews in Flutter</em></strong></a><em>.</em></p><p>This is what we are going to implement:</p><ul><li><strong>WebView Tab</strong>, with custom on long-press link/image preview, and how to move from one tab to another without losing the WebView state;</li><li><strong>Browser App Bar</strong> with the current URL and all popup menu actions such as opening a <strong>new tab</strong>, a <strong>new incognito tab</strong>, saving the current URL to the <strong>favorite list</strong>, saving a page to <strong>offline usage</strong>, viewing the <strong>SSL Certificate</strong> used by the website, enable <strong>Desktop Mode</strong>, etc. (features similar to the Google Chrome App);</li><li><strong>Developer console</strong>, where you can <strong>execute JavaScript code</strong>, see some <strong>network info</strong>, manage the browser storage such as <strong>cookies</strong>,<strong> </strong>window.localStorage , etc;</li><li><strong>Settings page</strong>, where you can update the browser general settings and <a href="https://github.com/pichillilorenzo/flutter_inappwebview#inappwebview-options">enable/disable all the features</a> offered by the <a href="https://github.com/pichillilorenzo/flutter_inappwebview#inappwebview-options">flutter_inappwebview</a> for each WebView Tab, such as enabling/disabling JavaScript, caching, scrollbars, setting custom user-agent, etc., and all the Android and iOS-specific features;</li><li><strong>Save</strong> and <strong>restore</strong> the current Browser state.</li></ul><p>Instead, about the app state management, we are going to use the <a href="https://pub.dev/packages/provider">provider</a> package.</p><p>The two main models used to realize this Browser app are the BrowserModel and the WebViewModel , which contains info and data of the Browser, such as the list of all WebView tabs and the current WebView tab displayed. They will be used also to save and restore the Browser state. To save and restore these models, we are going to use the <a href="https://pub.dev/packages/shared_preferences">shared_preferences</a> package.</p><p>Because the code could be very long, I’m going to show only little parts of the code or just pseudo-code. However, the <strong>full code</strong> is available on <strong>Github</strong> at <a href="https://github.com/pichillilorenzo/flutter_browser_app">https://github.com/pichillilorenzo/flutter_browser_app</a>.</p><p>Also, this app is <strong>available on the Google Play Store</strong> at <a href="https://play.google.com/store/apps/details?id=com.pichillilorenzo.flutter_browser">https://play.google.com/store/apps/details?id=com.pichillilorenzo.flutter_browser</a></p><p>This is the <strong>final result</strong> we are going to have:</p><p><a href="https://drive.google.com/file/d/1wE2yUGwjNBiUy72GOjPIYyDXYQn3ewYn/view?usp=sharing">flutter_browser_inappwebview.mp4</a></p><h3>WebView Tab</h3><p>The first thing we are going to implement is the WebView Tab. Considering that we need to maintain the state of each WebView Tab and the ability to move from one to another, we could use the IndexedStack widget, where the index property is the current WebView Tab we want to show and children is the list of all WebView Tab opened in the Browser.</p><p>We also want to show a progress bar that indicates the current load progress of the WebView, so we use the Stack widget where the first child is the IndexedStack widget created before and the second one is a LinearProgressIndicator . We can image this to be something like this:</p><pre>var stackChildren = &lt;Widget&gt;[<br>  IndexedStack(<br>    index: browserModel.getCurrentTabIndex(),<br>    children: browserModel.webViewTabs,<br>  ),<br>  LinearProgressIndicator()<br>];<br><br>return Stack(<br>  children: stackChildren,<br>);</pre><p>Each WebView Tab will be an instance of our custom WebViewTab widget, that is a StatefulWidget containing the InAppWebView instance (the real WeView), and the InAppWebViewController to control it. Each WebView Tab will have its GlobalKey to be distinguishable from the other browser tabs and a WebViewModel instance that contains the necessary data, such as the current URL and its WebView settings, to be able to restore them when the App is completely closed and reopened by the user.</p><p>For each WebView, the most important data we want to save is the current URL (also when it updates!), the page title, if it is secure or not, its favicon, its tab index, and its settings.</p><p>To track URL changes, we use the onLoadStart , onLoadStop and onUpdateVisitedHistory events. To listen to the website progress change, we use the onProgressChanged event. When the website is loaded, we use onLoadStop to get the website title, its favicon and we check if it is secure or not, based on the <strong>HTTPS protocol</strong>, the presence of an <strong>SSL certificate</strong> (<strong>X509Certificate</strong>), and any <strong>SSL errors</strong>.</p><p>Also, we want to implement our custom link/image preview. To do that, we use the onLongPressHitTestResult event, that detects the long-press event of the user inside the WebView. It returns a hitTestResult that contains useful information about what the user clicked, for example, if it is an image or a link. We check that and we show our custom AlertDialog :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6ws1FbLEqxtqtlsKKg9PQ.png" /><figcaption>On the left, we have a long-press link preview. Instead, on the right, we have detected that it is an image, so we show the corresponding alert dialog.</figcaption></figure><p>Also, we want to <strong>pause/resume</strong> the WebView when the App is paused/resumed and pause/resume JavaScript execution when we move from one WebView Tab to another.</p><p>To pause/resume WebView on Android, we can use InAppWebViewController.android.pause() and InAppWebViewController.android.resume() methods (on iOS, it is automatically managed by the WKWebView itself). Instead, to pause/resume JavaScript execution, we can use the InAppWebViewController.pauseTimers() and InAppWebViewController.resumeTimers() methods.</p><p><strong>NOTE</strong>: On Android, calling pause/resume timer methods will pause/resume JavaScript execution for all WebViews, instead, on iOS, it will pause/resume only for the specific WebView.</p><p>These methods will be called when the App Lifecycle State changes, that is when the didChangeAppLifecycleState event is fired by Flutter:</p><pre>@override<br>void didChangeAppLifecycleState(AppLifecycleState state) {<br>  if (_webViewController != null) {<br>    if (state == AppLifecycleState.paused) {</pre><pre>      if (Platform.<em>isAndroid</em>) {<br>        _webViewController?.android?.pause();<br>      }<br>      _webViewController?.pauseTimers();</pre><pre>    } else {</pre><pre>      if (Platform.<em>isAndroid</em>) {<br>        if (Platform.<em>isAndroid</em>) {<br>          _webViewController?.android?.resume();<br>        }<br>        _webViewController?.resumeTimers();<br>      } else if (Platform.<em>isIOS</em>) {<br>        var currentWebViewModel =<br>          Provider.<em>of</em>&lt;WebViewModel&gt;(context, listen: false);<br>        if (widget.webViewModel.tabIndex ==<br>          currentWebViewModel.tabIndex) {<br>          _webViewController?.resumeTimers();<br>        } else {<br>          _webViewController?.pauseTimers();<br>        }<br>      }</pre><pre>    }<br>  }<br>}</pre><p>Furthermore, we want to show a custom error page when there is a load error. For that case, we can listen to the onLoadError event and, for example, load a custom HTML into the WebView (or whatever you want):</p><pre>onLoadError: (controller, url, code, message) async {<br>  if (Platform.<em>isIOS </em>&amp;&amp; code == -999) {<br>    // NSURLErrorDomain<br>    return;<br>  }<br><br>  url = url ?? &#39;about:blank&#39;;<br><br>  _webViewController?.loadData(data: &quot;&quot;&quot;<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;<br>    &lt;style&gt;<br>    ${await _webViewController?.getTRexRunnerCss()}<br>    &lt;/style&gt;<br>    &lt;style&gt;<br>    .interstitial-wrapper {<br>        box-sizing: border-box;<br>        font-size: 1em;<br>        line-height: 1.6em;<br>        margin: 0 auto 0;<br>        max-width: 600px;<br>        width: 100%;<br>    }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    ${await _webViewController?.getTRexRunnerHtml()}<br>    &lt;div class=&quot;interstitial-wrapper&quot;&gt;<br>      &lt;h1&gt;Website not available&lt;/h1&gt;<br>      &lt;p&gt;Could not load web pages at &lt;strong&gt;$url&lt;/strong&gt; because:&lt;/p&gt;<br>      &lt;p&gt;$message&lt;/p&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>    &quot;&quot;&quot;, baseUrl: url, androidHistoryUrl: url);<br>},</pre><p>On Android, we can also disable the default error page using the Android-specific option disableDefaultErrorPage: true. This is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*4S_mBe_r_Q8guP9S8A1Cqg.gif" /><figcaption>Custom error page with the T-Rex Runner game.</figcaption></figure><p>Yes! You are right! It is the T-Rex Runner game! 🦖🦖🦖</p><h3>Browser App Bar</h3><p>The Browser App Bar and its actions are based on the Google Chrome mobile app. As you can see, it is composed of a search bar, a rectangle showing the number of tabs, and a dropdown menu.</p><p>It is an instance of AppBar where:</p><ul><li>if the Home Page option is enabled, the leading item is an IconButton ;</li><li>the title item is a Stack widget composed of a simple TextField that listen to the onSubmitted event, and an IconButton that indicates if the current Website is secure or not or if it is an offline website (a web archive);</li><li>the action items are an InkWell widget, that contains the number of current tabs and provides access to move to another tab or close them, and a PopupMenuButton widget, that contains the list of all available action, such as “New Tab”, “New Incognito Tab”, “Settings” page, “Developers” page, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*S0PwoRNR4NpcjpgB9iux0g.png" /><figcaption>Browser App Bar.</figcaption></figure><p>As you can see, dropdown actions are similar to the Google Chrome mobile app: we can move through the WebView history, save the current page as a web archive, save the website to the favorite list, enable desktop mode, reloading the page, taking a screenshot, etc.</p><p>The BrowserModel contains the favorite list, which is a simple list of FavoriteModel instances, which contains the favicon, URL, and title of each webpage saved as a favorite. The BrowserModel contains also a Map&lt;String, WebArchiveModel&gt; that represents the Web Archives saved using the InAppWebViewController.android.saveWebArchive method (at this moment, this method is available only on Android) to download the webpages in order to use them offline.</p><p>Instead, the WebView Tab history is provided by the InAppWebViewController.getCopyBackForwardList method, which returns the list of visited URLs and titles during the current session.</p><p>If we click on the “Find on page” action, the Browser App Bar will show the corresponding AppBar widget which manages the “Find on” WebView feature through a TextField widget and 3 IconButtons as actions, allowing us to search words using the InAppWebViewController.findAllAsync(find: &quot;&quot;) method, moving from one result to another using the InAppWebViewController.findNext(forward: ) method, and clear the matches found using the InAppWebViewController.clearMatches method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ULzchZOEnuAxiRKpbhUHvA.png" /><figcaption>Find on page App Bar.</figcaption></figure><p>So, the Browser App Bar will be a Widget that implements PreferredSizeWidet :</p><pre>class BrowserAppBar extends StatefulWidget<br>    implements PreferredSizeWidget {<br>  BrowserAppBar({Key key})<br>      : preferredSize = Size.fromHeight(kToolbarHeight),<br>        super(key: key);<br><br>  @override<br>  _BrowserAppBarState createState() =&gt; _BrowserAppBarState();<br><br>  @override<br>  final Size preferredSize;<br>}<br><br>class _BrowserAppBarState extends State&lt;BrowserAppBar&gt; {<br>  bool _isFindingOnPage = false;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return _isFindingOnPage<br>        ? FindOnPageAppBar(<br>            hideFindOnPage: () {<br>              setState(() {<br>                _isFindingOnPage = false;<br>              });<br>            },<br>          )<br>        : WebViewTabAppBar(<br>            showFindOnPage: () {<br>              setState(() {<br>                _isFindingOnPage = true;<br>              });<br>            },<br>          );<br>  }<br>}</pre><p>where FindOnPageAppBar and WebViewTabAppBar are AppBar instances.</p><h4>SSL Certificate Viewer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*MmCiRNWPYlG4zortqsv56g.gif" /></figure><p>As you can see, on the left side of the website URL there will be a green lock icon if the current website is using a valid SSL Certificate (we check it through onReceivedServerTrustAuthRequest WebView event) or if it is local content, otherwise, a grey outline info icon will be shown.</p><p>If you click on it, the app shows a custom popup dialog, implemented using a custom PageRoute class in order to allow us to create a new page route with transparent background.</p><p>If you click on “Details” and then on “Certificate info”, you can see an AlertDialog widget with all the X509 Certificate details.</p><h4>Move from one WebView Tab to another</h4><p>Because we have the list of all WebView Tab saved in our BrowserModel and each WebView Tab has its GlobalKey , we can change the displayed WebView updating the current WebView Tab index with the one we want to display.</p><p>We can achieve this in multiple ways, for example using a simple ListView where each child shows the WebView Tab title, favicon and URL, and, when a user clicks on it, we update the current WebView Tab index of our BrowserModel instance with the index of the child clicked.</p><p>In this sample App, I implemented it using a custom widget called TabViewer that uses a GestureDetector widget to listen to vertical drag events in order to mimic the behavior of the Google Chrome mobile app. Using the Timer class and the Transform widget, I obtained this effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*4GuGYHeUtaUoKYLQPyrPvQ.gif" /><figcaption>WebView Tab Viewer.</figcaption></figure><h3>Developer Console</h3><p>The Developer Console page contains a TabBarView with 3 tabs:</p><ul><li>JavaScript Console: where you can see console logs and execute JavaScript code as if you were on the JavaScript Console of the Google Chrome desktop version;</li><li>Network Info: where you can see all the resources loaded for the main frame, such as images, XMLHttpRequests, etc;</li><li>Storage Manager: where you can manage cookies, web storage, and HTTP auth credentials.</li></ul><p>To listen to JavaScript console logs, we use the onConsoleMessage WebView event on our WebView Tab, instead, to execute JavaScript code, we use the InAppWebViewController.evaluateJavascript(source: &quot;&quot;) method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*CbjrFQmOz_MIXK_xrkXJXA.gif" /><figcaption>Developer Console Page.</figcaption></figure><p>Each console log message and JavaScript result will be added to the list displayed in the JavaScript Console Tab. Also, we can move through our JavaScript code history and clear the current list.</p><p>To listen to the resources loading, we use the onLoadResource WebView event on our WebView Tab. Each resource will be added to the list displayed in the Network Info Tab.</p><p>Instead, the Storage Manager Tab will use the CookieManager class to manages cookies, InAppWebViewController.webStorage to manage local and session storage, HttpAuthCredentialDatabase to manage HTTP Auth credentials, and WebStorageManager that manages web storage in general, such as the Application Cache API, the Web SQL Database API, and the HTML5 Web Storage API (on Android it is implemented using <a href="https://developer.android.com/reference/android/webkit/WebStorage.html">WebStorage</a>, instead, on iOS it is implemented using <a href="https://developer.apple.com/documentation/webkit/wkwebsitedatastore">WKWebsiteDataStore.default()</a>).</p><h3>Settings Page</h3><p>This page contains all the Browser settings and also the current WebView Tab settings. It also contains a TabBarView with 3 tabs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*KFgAWuoqDLegoTUO11TMug.gif" /></figure><ul><li>Cross-platform options, such as the User-Agent, enable/disable JavaScript, enable/disable zoom support, etc.;</li><li>Android-specific options, such as enable/disable DOM Storage API and Database storage API, cache mode, etc.;</li><li>iOS-specific options, such as enable/disable over scroll, native link preview, etc.</li></ul><p>Each tab contains a ListView widget where each child could be a ListTile widget, a SwitchListTile widget or a Container with a DropdownButton widget that represents a WebView option with a little description.</p><h3>Save and Restore the Browser state</h3><p>As said before, to save and restore the Browser state, such as the current list of the WebView Tabs, we are going to use the <a href="https://pub.dev/packages/shared_preferences">shared_preferences</a> package.</p><p>Each time the App recognizes that something is changed in the BrowserModel and in the current WebViewModel (such as the current URL or the title) using the addListener method provided by the ChangeNotifier class, we encode the BrowserModel instance into a JSON string and we save it using the <a href="https://pub.dev/packages/shared_preferences">shared_preferences</a> package.</p><p>To avoid saving on quick sequential changes, we don’t save it immediately, but we wait to check if during a certain range of time another “save” request has been made. Then, we save it.</p><p>When we restore the Browser state during the App restart, we decode the JSON string and we add/override all the necessary data into the current BrowserModel instance.</p><p>We can achieve this using the following 3 methods (save, flush, and restore) defined inside the BrowserModel class:</p><pre>DateTime _lastTrySave = DateTime.now();<br>Timer _timerSave;<br>Future&lt;void&gt; save() async {<br>  _timerSave?.cancel();<br><br>  if (DateTime.now().difference(_lastTrySave) &gt;= Duration(milliseconds: 400)) {<br>    _lastTrySave = DateTime.now();<br>    await flush();<br>  } else {<br>    _lastTrySave = DateTime.now();<br>    _timerSave = Timer(Duration(milliseconds: 500), () {<br>      save();<br>    });<br>  }<br>}<br><br>Future&lt;void&gt; flush() async {<br>  SharedPreferences prefs = await SharedPreferences.<em>getInstance</em>();<br>  await prefs.setString(&quot;browser&quot;, json.encode(toJson()));<br>}<br><br>Future&lt;void&gt; restore() async {<br>  SharedPreferences prefs = await SharedPreferences.<em>getInstance</em>();<br>  Map&lt;String, dynamic&gt; browserData;<br>  try {<br>    browserData = await json.decode(prefs.getString(&quot;browser&quot;));<br>  } catch (e) {<br>    print(e);<br>    return;<br>  }<br><br>  this.clearFavorites();<br>  this.closeAllTabs();<br>  this.clearWebArchives();<br><br>  List&lt;Map&lt;String, dynamic&gt;&gt; favoritesList = browserData[&quot;favorites&quot;]?.cast&lt;Map&lt;String, dynamic&gt;&gt;();<br>  List&lt;FavoriteModel&gt; favorites = favoritesList?.map((e) =&gt; FavoriteModel.<em>fromMap</em>(e))?.toList() ?? [];<br><br>  Map&lt;String, dynamic&gt; webArchivesMap = browserData[&quot;webArchives&quot;]?.cast&lt;String, dynamic&gt;() ?? {};<br>  Map&lt;String, WebArchiveModel&gt; webArchives = webArchivesMap.map((key, value) =&gt;<br>      MapEntry(key, WebArchiveModel.<em>fromMap</em>(value?.cast&lt;String, dynamic&gt;())));<br><br>  BrowserSettings settings = BrowserSettings.<em>fromMap</em>(browserData[&quot;settings&quot;]?.cast&lt;String, dynamic&gt;()) ?? BrowserSettings();<br>  List&lt;Map&lt;String, dynamic&gt;&gt; webViewTabList = browserData[&quot;webViewTabs&quot;]?.cast&lt;Map&lt;String, dynamic&gt;&gt;();<br>  List&lt;WebViewTab&gt; webViewTabs = webViewTabList<br>      ?.map((e) =&gt; WebViewTab(<br>        key: GlobalKey(),<br>        webViewModel: WebViewModel.<em>fromMap</em>(e),<br>      ))<br>      ?.toList() ?? [];<br>  webViewTabs.sort((a, b) =&gt; a.webViewModel.tabIndex.compareTo(b.webViewModel.tabIndex));<br><br><br>  this.addFavorites(favorites);<br>  this.addWebArchives(webArchives);<br>  this.updateSettings(settings);<br>  this.addTabs(webViewTabs);<br><br>  int currentTabIndex = browserData[&quot;currentTabIndex&quot;] ?? this._currentTabIndex;<br>  currentTabIndex = min(currentTabIndex, this._webViewTabs.length - 1);<br><br>  if (currentTabIndex &gt;= 0)<br>    this.showTab(currentTabIndex);<br>}</pre><h3>Conclusion</h3><p>In this article, we used the <a href="https://github.com/pichillilorenzo/flutter_inappwebview">flutter_inappwebview</a> plugin to create a <strong>Full-Featured Browser App</strong>. The plugin is in continuous development (at the time of this writing, the latest release is 4.0.0+4) and I recommend you check out the <a href="https://pub.dev/documentation/flutter_inappwebview/latest/">API Reference</a> to find out all the features and the previous article that introduces the <strong>flutter_inappwebview</strong> plugin here: <a href="https://medium.com/flutter-community/inappwebview-the-real-power-of-webviews-in-flutter-c6d52374209d"><strong><em>InAppWebView: The Real Power of WebViews in Flutter</em></strong></a>. For any new feature request/bug fix, you can use the issue section of the repository.</p><p>If you found this useful and you like the <a href="https://github.com/pichillilorenzo/flutter_inappwebview">flutter_inappwebview</a> plugin and this App project, give a star to:</p><ul><li>Flutter plugin: <a href="https://github.com/pichillilorenzo/flutter_inappwebview">https://github.com/pichillilorenzo/flutter_inappwebview</a></li><li>Browser App: <a href="https://github.com/pichillilorenzo/flutter_browser_app">https://github.com/pichillilorenzo/flutter_browser_app</a> (<strong>Google Play Store link</strong>: <a href="https://play.google.com/store/apps/details?id=com.pichillilorenzo.flutter_browser">https://play.google.com/store/apps/details?id=com.pichillilorenzo.flutter_browser</a>)</li></ul><p>That’s all for today, thanks for your attention!</p><p><a href="https://www.twitter.com/FlutterComm">https://www.twitter.com/FlutterComm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c8f2923c574" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/creating-a-full-featured-browser-using-webviews-in-flutter-9c8f2923c574">Creating a Full-Featured Browser using WebViews in Flutter</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[InAppWebView: The Real Power of WebViews in Flutter]]></title>
            <link>https://medium.com/flutter-community/inappwebview-the-real-power-of-webviews-in-flutter-c6d52374209d?source=rss-11e6aac5f656------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6d52374209d</guid>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[in-app-browsers]]></category>
            <category><![CDATA[flutter-webview]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[wkwebview]]></category>
            <dc:creator><![CDATA[Lorenzo Pichilli]]></dc:creator>
            <pubDate>Thu, 02 Jul 2020 14:39:00 GMT</pubDate>
            <atom:updated>2020-07-21T14:55:26.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6V43U_Bgf8T5PZLQF-M3Q.png" /><figcaption>Flutter InAppWebView.</figcaption></figure><p>What is <a href="https://github.com/pichillilorenzo/flutter_inappwebview">flutter_inappwebview</a> ? It’s a Flutter plugin that allows you to incorporate <strong>WebView widgets</strong> into your Flutter app, to use <strong>headless WebViews</strong>, or to use <strong>In-App browsers</strong>.</p><p>So, what’s the difference between <a href="https://pub.dev/packages/webview_flutter">webview_flutter</a> (Official flutter plugin) and <a href="https://pub.dev/packages/flutter_webview_plugin">flutter_webview_plugin</a> ? <br>Compared to all other WebView plugins, it is <strong>feature-rich</strong>: a lot of <strong>events</strong>, <strong>methods</strong>, and <strong>options</strong> to control WebViews. Furthermore, they do not have good documentation about their API or, at least, it is not complete. Instead, every feature of flutter_inappwebview is almost all documented (just check the <a href="https://pub.dev/documentation/flutter_inappwebview/latest/index.html">API Reference on pub.dev</a>).</p><p>In this article, I’m going to present the main classes and some examples of the InAppWebView widget that people were asking about on the official <a href="https://github.com/pichillilorenzo/flutter_inappwebview">flutter_inappwebview repository</a> (issue section) and on StackOverflow.</p><h3>Main Classes Overview</h3><p>This is a list of the main classes that the plugin offers:</p><ul><li><a href="https://github.com/pichillilorenzo/flutter_inappwebview#inappwebview-class">InAppWebView</a>: Flutter Widget for adding an inline native WebView integrated into the flutter widget tree.</li><li><a href="https://github.com/pichillilorenzo/flutter_inappwebview#contextmenu-class">ContextMenu</a>: This class represents the WebView context menu.</li><li><a href="https://github.com/pichillilorenzo/flutter_inappwebview#headlessinappwebview-class">HeadlessInAppWebView</a>: Class that represents a WebView in headless mode. It can be used to run a WebView in background without attaching an InAppWebView to the widget tree.</li><li><a href="https://github.com/pichillilorenzo/flutter_inappwebview#inappbrowser-class">InAppBrowser</a>: In-App Browser using native WebView.</li><li><a href="https://github.com/pichillilorenzo/flutter_inappwebview#chromesafaribrowser-class">ChromeSafariBrowser</a>: In-App Browser using <a href="https://developer.android.com/reference/android/support/customtabs/package-summary">Chrome Custom Tabs</a> on Android / <a href="https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller">SFSafariViewController</a> on iOS.</li><li><a href="https://github.com/pichillilorenzo/flutter_inappwebview#inapplocalhostserver-class">InAppLocalhostServer</a>: This class allows you to create a simple server on http://localhost:[port]/. The default port value is 8080.</li><li><a href="https://github.com/pichillilorenzo/flutter_inappwebview#cookiemanager-class">CookieManager</a>: This class implements a singleton object (shared instance) which manages the cookies used by WebView instances.</li><li><a href="https://github.com/pichillilorenzo/flutter_inappwebview#httpauthcredentialdatabase-class">HttpAuthCredentialDatabase</a>: This class implements a singleton object (shared instance) that manages the shared HTTP auth credentials cache.</li><li><a href="https://github.com/pichillilorenzo/flutter_inappwebview#webstoragemanager-class">WebStorageManager</a>: This class implements a singleton object (shared instance) which manages the web storage used by WebView instances.</li></ul><p>In this article, I’m going to show in particular the InAppWebView widget, that is the most used/requested one.</p><h4>InAppWebView is a Widget like any other!</h4><p>Adding the InAppWebView widget into your app is very simple. It’s just a widget like any other Flutter widget: InAppWebView(initialUrl: &#39;https://github.com/flutter&#39;).</p><p><strong>NOTE</strong>: To use it on iOS, you need to opt-in for the embedded views preview by adding a boolean property to the app&#39;s Info.plist file, with the key io.flutter.embedded_views_preview and the value YES.</p><p>This widget has a set of initial attributes that you can use to initialize the WebView:</p><ul><li><strong>initialUrl</strong>: Initial URL that will be loaded;</li><li><strong>initialOptions</strong>: Initial WebView options that will be used;</li><li><strong>gestureRecognizers</strong>: specifies which gestures should be consumed by the WebView;</li><li><strong>initialData</strong>: Initial InAppWebViewInitialData that will be loaded, such as an HTML string;</li><li><strong>initialFile</strong>: Initial asset file that will be loaded (check the “<a href="https://github.com/pichillilorenzo/flutter_inappwebview#load-a-file-inside-assets-folder"><em>Load a file inside assets folder</em></a>” Section);</li><li><strong>initialHeaders</strong>: Initial headers that will be used;</li><li><strong>contextMenu</strong>: Context menu which contains custom menu items.</li></ul><p>The list of all available WebView options is quite long, for example, you can enable/disable JavaScript using the javascriptEnabled option or enable/disable cache using the cacheEnabled option. The full list of all options is available <a href="https://github.com/pichillilorenzo/flutter_inappwebview#inappwebview-options"><strong>here</strong></a>.</p><h4>Use InAppWebViewController to control your WebView</h4><p>Instead, to control the WebView, you have the InAppWebViewController class. This controller is returned by the onWebViewCreated callback when the WebView is ready to be used.<br>Through it, you can control your WebView or access its properties, such as the current URL using getUrl method. Other methods, for example, are loadUrl to load a new URL, postUrl to load a given URL with custom data using POST method, evaluateJavascript to evaluate JavaScript code into the WebView, and to get the result of the evaluation, takeScreenshot to take the screenshot (in PNG format) of the WebView’s visible viewport, getCertificate to get the <strong>SSL certificate</strong> for the main top-level page or null if there is no certificate. The full list of all methods you can use is quite long and available <a href="https://github.com/pichillilorenzo/flutter_inappwebview#inappwebviewcontroller-methods"><strong>here</strong></a>.</p><h4>InAppWebView Events</h4><p>The InAppWebView widget offers a <strong>variety of events</strong>! Here’s a few of them:</p><ul><li><strong>onLoadStart</strong>: event fired when the WebView starts to load an URL;</li><li><strong>onLoadStop</strong>: event fired when the WebView finishes loading an URL;</li><li><strong>onLoadHttpError: </strong>event fired when the WebView main page receives an HTTP error;</li><li><strong>onConsoleMessage</strong>: event fired when the WebView receives a JavaScript console message (such as console.log , console.error , etc.);</li><li><strong>shouldOverrideUrlLoading</strong>: gives the host application a chance to take control when a URL is about to be loaded in the current WebView;</li><li><strong>onDownloadStart</strong>: event fired when WebView recognizes a downloadable file;</li><li><strong>onReceivedHttpAuthRequest</strong>: event fired when the WebView received an HTTP authentication request. The default behavior is to cancel the request;</li><li><strong>onReceivedServerTrustAuthRequest</strong>: event fired when the WebView need to perform server trust authentication (certificate validation);</li><li><strong>onPrint</strong>: event fired when window.print() is called from JavaScript side;</li><li><strong>onCreateWindow</strong>: event fired when the InAppWebView requests the host application to create a new window, for example when trying to open a link with target=&quot;_blank&quot; or when window.open() is called by JavaScript side;</li></ul><p>and <strong>many many more</strong>! I recommend checking the API Reference to get more details. As for the WebView options and methods, the full list of all WebView events is quite long and available <a href="https://github.com/pichillilorenzo/flutter_inappwebview#inappwebview-events"><strong>here</strong></a>.</p><h4>InAppWebView Simple Example</h4><p>Here is a simple example that shows an InAppWebView widget, its current URL, and 3 buttons: one to go back, one to go forward, and another one to reload the current page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*8QYRJH1V2jyoBY_6Z0llHQ.gif" /><figcaption>InAppWebView example.</figcaption></figure><p>This is the full code example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a4dac146b3ff0ac63c16d3a67b50930/href">https://medium.com/media/8a4dac146b3ff0ac63c16d3a67b50930/href</a></iframe><h4>JavaScript Handlers (Channels)</h4><p>You can communicate with the JavaScript side and vice-versa. To add a JavaScript handler, you can use _webViewController.addJavaScriptHandler method, where you define the handlerName and a callback to be invoked when it is called by the JavaScript side. The callback can return data to be sent on the JavaScript side.</p><p>Instead, on the JavaScript side, to execute the callback handler and send data to Flutter, you need to use window.flutter_inappwebview.callHandler(handlerName &lt;String&gt;, ...args) method, where handlerName is a string that represents the handler name that your calling and args are optional arguments that you can send to the Flutter side.</p><p>In order to call window.flutter_inappwebview.callHandler(handlerName &lt;String&gt;, ...args) properly, you need to wait and listen to the JavaScript event flutterInAppWebViewPlatformReady. This event will be dispatched as soon as the platform (Android or iOS) is ready to handle the callHandler method.</p><p>Here is an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58e64a2022946933209354ca3ba317b8/href">https://medium.com/media/58e64a2022946933209354ca3ba317b8/href</a></iframe><h4>WebRTC in InAppWebView</h4><p>At this moment, <strong>WebRTC</strong> is supported only on Android, because, unfortunately, on iOS WKWebView doesn’t implement all the WebRTC API (you can follow this issue: <a href="https://github.com/pichillilorenzo/flutter_inappwebview/issues/200"><strong>#200</strong></a>).</p><p>I’m going to show an example using <a href="https://appr.tc/">https://appr.tc/</a> to test WebRTC feature. It’s a video chat demo app based on WebRTC (<a href="https://github.com/webrtc/apprtc">https://github.com/webrtc/apprtc</a>).</p><p>To request permissions about the camera and microphone, you can use the <a href="https://pub.dev/packages/permission_handler">permission_handler</a> plugin. Also, you need to set the WebView option mediaPlaybackRequiresUserGesture to false in order to autoplay HTML5 audio and video.</p><p>Furthermore, on Android, you need to implement the androidOnPermissionRequest event (it’s an Android-specific event), that is an event fired when the WebView is requesting permission to access a specific resource (that is the Android native <a href="https://developer.android.com/reference/android/webkit/WebChromeClient#onPermissionRequest(android.webkit.PermissionRequest)">WebChromeClient.onPermissionRequest event</a>). In this case, this event is used to grant permissions for the WebRTC API. Also, you need to add these permissions in the AndroidManifest.xml:</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.RECORD_AUDIO&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.MODIFY_AUDIO_SETTINGS&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.VIDEO_CAPTURE&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.AUDIO_CAPTURE&quot; /&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Tn65MhV5HyENdSAGSP8Flg.gif" /><figcaption>WebRTC example.</figcaption></figure><p>Here is the full code example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c277046868e2535bc9e01544542ca30/href">https://medium.com/media/0c277046868e2535bc9e01544542ca30/href</a></iframe><h4>How to enable download files in InAppWebView</h4><p>InAppWebView can recognize downloadable files in both Android and iOS platforms. To be able to recognize downloadable files, you need to set the useOnDownloadStart: true option, and then you can listen to the onDownloadStart event.</p><p>On Android you need to add write permission inside your AndroidManifest.xml file:</p><pre>&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;</pre><p>Then, you need to ask permission using the <a href="https://pub.dev/packages/permission_handler">permission_handler</a> plugin. Instead, to effectively download your file, you can use the <a href="https://pub.dev/packages/flutter_downloader">flutter_downloader</a> plugin.</p><p>Here is a complete example using <a href="http://ovh.net/files/">http://ovh.net/files/</a> (in particular, the <a href="http://ovh.net/files/1Mio.dat">http://ovh.net/files/1Mio.dat</a> as URL) to test the download:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f4d96bb0c3f85e745986b923e6cff67/href">https://medium.com/media/1f4d96bb0c3f85e745986b923e6cff67/href</a></iframe><p>As you can see, I’m using also the <a href="https://pub.dev/packages/path_provider">path_provider</a> plugin to get the folder where I want to save the file.</p><h4>Allow Self-signed SSL Certificates</h4><p>To allow self-signed SSL certificates, you can use the onReceivedServerTrustAuthRequest event and simply return to proceed with the request:</p><pre>onReceivedServerTrustAuthRequest: (controller, challenge) async {<br>  return ServerTrustAuthResponse(action: ServerTrustAuthResponseAction.PROCEED);<br>},</pre><h4>How to manage popup windows opened with target=”_blank” or “window.open”</h4><p>To manage popup windows when a user clicks on a link with target=&quot;_blank&quot; or through JavaScript code using window.open , you can use the onCreateWindow event. On Android, to be able to allow this event, you need to set the supportMultipleWindows option to true . Also, in order to be able to allow the usage of JavaScript, you need to set the javaScriptCanOpenWindowsAutomatically to true .</p><p>If you want to manage these requests, you should return true from this event, otherwise, the default implementation of this event does nothing and hence returns false .</p><p>The CreateWindowRequest represents the navigation request which contains a windowId that can be used to create, for example, a new InAppWebView instance. This windowId is used by the native code to map the request and the WebView to be used to manage that request.</p><p>Also, CreateWindowRequest contains the url of the request (on Android, if the popup is opened using JavaScript with window.open , it will be null ), but if you need to maintain the Window JavaScript object reference (created using window.open method), for example, to call window.close method, then you should create the new WebView with the windowId , without using the url .</p><p>Here is a simple example that shows an AlertDialog when the user clicks on the link:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/035485c4250a8c31ffb0ec305158a859/href">https://medium.com/media/035485c4250a8c31ffb0ec305158a859/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*fiuMpP97wZ-bUfr4nNnWew.gif" /><figcaption>onCreateWindow Event - Popup window example.</figcaption></figure><h4>Manage platform URLs such as whatsapp:, fb:, tel:, mailto:, etc.</h4><p>Generally, a WebView knows nothing on how to manage whatsapp: , tel: or fb: protocol/scheme. To capture the requests made with these custom protocols/schemes, you can use the shouldOverrideUrlLoading event (you need to enable it with useShouldOverrideUrlLoading: true option).</p><p>This way you can cancel the request made for the WebView and, instead, open the App, for example, using the <a href="https://pub.dev/packages/url_launcher">url_launcher</a> plugin:</p><pre>initialOptions: InAppWebViewGroupOptions(<br>  crossPlatform: InAppWebViewOptions(<br>      debuggingEnabled: true,<br>      useShouldOverrideUrlLoading: true<br>  ),<br>),<br>shouldOverrideUrlLoading: (controller, request) async {<br>  var url = request.url;<br>  var uri = Uri.<em>parse</em>(url);<br><br>  if (![&quot;http&quot;, &quot;https&quot;, &quot;file&quot;,<br>    &quot;chrome&quot;, &quot;data&quot;, &quot;javascript&quot;,<br>    &quot;about&quot;].contains(uri.scheme)) {<br>    if (await canLaunch(url)) {<br>      // Launch the App<br>      await launch(<br>        url,<br>      );<br>      // and cancel the request<br>      return ShouldOverrideUrlLoadingAction.<em>CANCEL</em>;<br>    }<br>  }<br><br>  return ShouldOverrideUrlLoadingAction.<em>ALLOW</em>;<br>},</pre><h4>Manage WebView Cookies</h4><p>To manage WebView cookies, you can use the <a href="https://github.com/pichillilorenzo/flutter_inappwebview#cookiemanager-class">CookieManager</a> class, which implements a singleton object (shared instance). On Android, it is implemented using the <a href="https://developer.android.com/reference/android/webkit/CookieManager">CookieManager</a> class. On iOS, it is implemented using the <a href="https://developer.apple.com/documentation/webkit/wkhttpcookiestore">WKHTTPCookieStore</a> class.</p><p>Here is an example of how to set a cookie:</p><pre>CookieManager _cookieManager = CookieManager.<em>instance</em>();<br><br>final expiresDate =<br>    DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;</pre><pre>_cookieManager.setCookie(<br>  url: &quot;https://flutter.dev/&quot;,<br>  name: &quot;session&quot;,<br>  value: &quot;54th5hfdcfg34&quot;,<br>  domain: &quot;.flutter.dev&quot;,<br>  expiresDate: expiresDate,<br>  isSecure: true,<br>);</pre><h4>Custom context menus</h4><p>You can customize WebView’s context menu adding custom menu items, and/or hiding the default system menu items. For each custom menu item, you can declare a callback action to be invoked when the user clicks on it. As an example, I will add a custom menu item named Special and I will define a callback action that shows a JavaScript window.alert to the user with the text selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*XJ6RCi7ur4b_Rhgyab63rw.gif" /><figcaption>Custom menu item example.</figcaption></figure><p>Here is the full code example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a372d2cde1e41777b215cdd659a74a78/href">https://medium.com/media/a372d2cde1e41777b215cdd659a74a78/href</a></iframe><h4>Conclusion</h4><p>In this article, I made a little introduction to the <a href="https://github.com/pichillilorenzo/flutter_inappwebview">flutter_inappwebview</a> plugin, in particular, about the InAppWebView widget. The plugin is in continuous development (at the time of this writing, the latest release is 4.0.0) and I recommend you check out the API Reference to find out all the features. For any new feature request/bug fix, you can use the issue section of the repository.</p><p>The next article will be on how to implement a <strong>Full-Featured Browser</strong> using this plugin: <a href="https://medium.com/flutter-community/creating-a-full-featured-browser-using-webviews-in-flutter-9c8f2923c574"><strong><em>Creating a Full-Featured Browser using WebViews in Flutter</em></strong></a>.</p><p>That’s all for today! I hope it has opened new use cases for your Flutter apps.</p><p><a href="https://www.twitter.com/FlutterComm">https://www.twitter.com/FlutterComm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6d52374209d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/inappwebview-the-real-power-of-webviews-in-flutter-c6d52374209d">InAppWebView: The Real Power of WebViews in Flutter</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jackson-js: Examples for client and server side (Part 2)]]></title>
            <link>https://medium.com/@pichillilorenzo/jackson-js-examples-for-client-and-server-side-part-2-7e66df74c851?source=rss-11e6aac5f656------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e66df74c851</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[json-parse]]></category>
            <category><![CDATA[json-serialization]]></category>
            <category><![CDATA[json-stringify]]></category>
            <dc:creator><![CDATA[Lorenzo Pichilli]]></dc:creator>
            <pubDate>Tue, 05 May 2020 16:37:41 GMT</pubDate>
            <atom:updated>2020-05-05T18:22:24.749Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jackson-js: Examples for client (Angular) and server (Node.js) side (Part 2)</h3><p><em>This is the second part of a two-part series. You should read the first part “</em><a href="https://medium.com/@pichillilorenzo/jackson-js-powerful-javascript-decorators-to-serialize-deserialize-objects-into-json-and-vice-df952454cf"><em>Jackson-js: Powerful JavaScript decorators to serialize/deserialize objects into JSON and vice versa (Part 1)</em></a><em>”.</em></p><p>In this article, I will give a simple example using the <a href="https://github.com/pichillilorenzo/jackson-js">jackson-js</a> library with Angular 9 for the client side and two examples for the server side: one using Node.js + <a href="http://expressjs.com/">Express</a> + SQLite3 (with <a href="https://sequelize.org/">Sequelize 5</a>) and another one using Node.js + <a href="https://github.com/strongloop/loopback-next">LoopBack 4</a>.</p><p>Full code examples can be found in <a href="https://github.com/pichillilorenzo/jackson-js-examples">this repository</a>.</p><h3>Client side: Angular 9</h3><p>For the client side, we will create a very basic Angular 9 application consisting of 2 models (<em>Writer</em> and <em>Book</em>), 2 services to communicate with the server side, and a home component that will call these 2 services.</p><h4>Models</h4><p><strong>Writer model</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b57290e40e5a3293009cd1a277b3fc16/href">https://medium.com/media/b57290e40e5a3293009cd1a277b3fc16/href</a></iframe><p><strong>Book model</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29b7428ef016297769e0a5000c73a28b/href">https://medium.com/media/29b7428ef016297769e0a5000c73a28b/href</a></iframe><h4>Services</h4><p>Services that will be used to get/push data from/to the server side.</p><p><strong>Writer service</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b1af73c90530b9c4b8310af05676196/href">https://medium.com/media/8b1af73c90530b9c4b8310af05676196/href</a></iframe><p><strong>Book service</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87e427619cec09db5ceb5bcc18991b85/href">https://medium.com/media/87e427619cec09db5ceb5bcc18991b85/href</a></iframe><h4>Home Component</h4><p>A very basic component that will be used to call each method of each service and to print the responses data to the browser console.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cb245612af70330160a222a526c72d6/href">https://medium.com/media/8cb245612af70330160a222a526c72d6/href</a></iframe><h3>Server side: Node.js + Express + SQLite3 (with Sequelize 5)</h3><p>For this case, we will implement a simple Node.js <a href="http://expressjs.com/"><em>Express</em></a> application using an in-memory <em>SQLite 3</em> database (with <a href="https://sequelize.org/"><em>Sequelize 5</em></a>), consisting of 2 entities (Writer and Book). This Express application will offer endpoints used by the client side to get/add data from/to the database. Also, it will have 2 Jackson Views has an example: ProfileViews.public and ProfileViews.registered .</p><h4>Models</h4><p>Because each class model extends the <em>Sequelize.Model</em> class, we need to ignore its enumerable properties using the <em>@JsonIgnoreProperties</em> decorator, otherwise, serialization won’t work properly.</p><p><strong>Writer model</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e674233ac3a3c8b6dbc38e225de9775/href">https://medium.com/media/2e674233ac3a3c8b6dbc38e225de9775/href</a></iframe><p>As we can see, the writer model has a static creator method named buildFromJson decorated with the <em>@JsonCreator</em> decorator. This method will be used during deserialization in order to create an instance of the Writer class model using Sequelize 5 API.</p><p>Also, I defined a getter method for the books property using <em>@JsonGetter</em> in order to get the associated data (one-to-many relationship with Book ) through the Sequelize get() method. Without this, during serialization, the books property will be empty. Another way is to call the Sequelize get() or toJSON() method for each model that needs to be serialized before serialization. This is needed because Sequelize wraps all it’s return values in a virtual object that contains metadata, so we unwrap them.</p><p><strong>Book model</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bb35a0db442a966659b6c60eff18afc/href">https://medium.com/media/8bb35a0db442a966659b6c60eff18afc/href</a></iframe><p>Same as Writer , we have a static creator method used to build the Book instance and a getter method for the writer property. Also, in the <em>@JsonIgnoreProperties</em> decorator, I added the writerId property (that is automatically added by Sequelize) in order to exclude it from the generated JSON content.</p><h3>Server side: Node.js + LoopBack 4</h3><p>Instead, for this case, we will implement a simple <a href="https://github.com/strongloop/loopback-next"><em>LoopBack 4</em></a> application using a file data source as the database. This application will offer endpoints used by the client side to get/add data from/to the database. Also here, it will have 2 Jackson Views has an example: ProfileViews.public and ProfileViews.registered .</p><h4>Models</h4><p>LoopBack 4 Entity class doesn’t wrap our entities, so we don’t need to use <em>@JsonIgnoreProperties</em> decorator like on Sequelize.</p><p><strong>Writer model</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f85c3e76078c7962fed663b37a72db2/href">https://medium.com/media/4f85c3e76078c7962fed663b37a72db2/href</a></iframe><p><strong>Book model</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/152d35f395bd3b907e257521b598137d/href">https://medium.com/media/152d35f395bd3b907e257521b598137d/href</a></iframe><h4>LoopBack Custom “object-mapper” Interceptor</h4><p>LoopBack gives us the ability to create custom interceptors. In this case, I created a global interceptor called object-mapper that will be used by the controllers to read and write JSON content using the jackson-js library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00a074448e2794d7b276852c22534144/href">https://medium.com/media/00a074448e2794d7b276852c22534144/href</a></iframe><h3>Jackson Context Groups</h3><p>For both server side examples, I defined 2 context groups: writerContextApi and bookContextApi . They are used to enable/disable specific decorators based on which API endpoint the client is calling.</p><ul><li>writerContextApi : it is used when the client is calling /writers/* endpoints to enable the <em>@JsonManagedReference</em> decorator and disable the <em>@JsonIgnoreProperties </em>decorator on the Writer.books property and to enable the <em>@JsonBackReference</em> decorator on the Book.writer property;</li><li>bookContextApi : it is used when the client is calling /books/* endpoints to enable the <em>@JsonIgnoreProperties </em>decorator on the Writer.books property.</li></ul><h3>RESTful API Endpoints available</h3><p>Both servers run at http://localhost:8000 and, for each one, I created a function named initDB that will initialize the database with fake data at server startup.</p><p>Endpoints are:</p><ul><li>/writers/public : get (“GET”) all writers (with books) using ProfileViews.public Jackson view;</li><li>/writers : get (“GET”) all writers (with books) or add (“POST”) a new writer;</li><li>/books/public : get (“GET”) all books (each one with its writer) using ProfileViews.public Jackson view;</li><li>/books : get (“GET”) all books (each one with its writer) or add (“POST”) a new book.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*fHjTmZbKDcFbV096MTTKCQ.png" /><figcaption>The parsed response of the client side after calling “/writers/public” endpoint of the Node.js + LoopBack 4 server.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*ZdSMvplcZUbqpbAKSYkJ5g.png" /><figcaption>The parsed response of the client side after calling “/books” endpoint of the Node.js + Express + SQLite3 (with Sequelize 5) server.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e66df74c851" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jackson-js: Powerful JavaScript decorators to serialize/deserialize objects into JSON and vice…]]></title>
            <link>https://itnext.io/jackson-js-powerful-javascript-decorators-to-serialize-deserialize-objects-into-json-and-vice-df952454cf?source=rss-11e6aac5f656------2</link>
            <guid isPermaLink="false">https://medium.com/p/df952454cf</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[json-serialization]]></category>
            <category><![CDATA[json-stringify]]></category>
            <category><![CDATA[json-parse]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Lorenzo Pichilli]]></dc:creator>
            <pubDate>Tue, 05 May 2020 16:36:33 GMT</pubDate>
            <atom:updated>2020-05-13T16:09:58.099Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jackson-js: Powerful JavaScript decorators to serialize/deserialize objects into JSON and vice versa (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*hMIqEMzV6ga93WL9HZEsyg.png" /><figcaption>JSON logo</figcaption></figure><p>After many hours of development, I finally released the first version of the <a href="https://github.com/pichillilorenzo/jackson-js">jackson-js</a> library. As the name implies, <a href="https://github.com/pichillilorenzo/jackson-js">jackson-js</a> decorators are heavily inspired by the Java annotations of the famous Java <a href="https://github.com/FasterXML/jackson">FasterXML/jackson library</a>.</p><p>You can install it using npm install —-save jackson-js and it can be used on both <strong>client</strong> (browser) and <strong>server</strong> (Node.js) side.</p><h4>Why this library? What’s the difference between using this library instead of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">JSON.parse</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify</a> ?</h4><p>For simple cases, you don’t need this library, of course, you can just use JSON.parse and JSON.stringify to serialize/deserialize JSON.</p><p>With <a href="https://github.com/pichillilorenzo/jackson-js">jackson-js</a> , you can easily manipulate your JavaScript objects/values serialization/deserialization using decorators such as @JsonProperty() , @JsonFormat() , @JsonIgnore() , etc. However, this library uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">JSON.parse</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify</a> under the hood.</p><p>Furthermore:</p><ul><li>it not only deserialize JSON text into a JavaScript object, it also converts it into an <strong>instance of the class</strong> specified in the context option (similar packages are: <a href="https://github.com/typestack/class-transformer">class-transformer</a> and <a href="https://github.com/JohnWeisz/TypedJSON">TypedJSON</a>); instead, with JSON.parse you will get just a simple plain (literal) JavaScript object (just <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a> type);</li><li>it supports more advanced Object concepts such as <strong>polymorphism</strong> and <strong>Object identity</strong>;</li><li>it supports <strong>cyclic object</strong> serialization/deserialization;</li><li>it supports serialization/deserialization of other native JavaScript types: Map , Set , BigInt , Typed Arrays (such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array">Int8Array</a>);</li></ul><p>This library can be useful in more complex cases, for example when you want to:</p><ul><li>manipulate JSON in depth;</li><li>restore a JavaScript type (a similar package is <a href="https://github.com/typestack/class-transformer">class-transformer</a>);</li><li>preserve type information (using polymorphic type handling decorators: @JsonTypeInfo, @JsonSubTypes, and @JsonTypeName. A similar package is <a href="https://github.com/JohnWeisz/TypedJSON">TypedJSON</a>);</li><li>hide some properties for certain HTTP endpoints or some other external service;</li><li>have different JSON response for some external application or manage different JSON data coming from other application (for example you need to communicate with a Spring Boot application that uses different JSON Schema for the same model or with other applications made with Python, PHP, etc…);</li><li>manage cyclic references;</li><li>manage other JavaScript native types such as Maps and Sets;</li><li>etc.</li></ul><p>Most of the use cases of the Java <a href="https://github.com/FasterXML/jackson">FasterXML/jackson</a> annotations are similar or equal.</p><p>In this article, I will present a basic example for each decorator.</p><h3>ObjectMapper, JsonParser and JsonStringifier classes</h3><p>The main classes that <a href="https://github.com/pichillilorenzo/jackson-js">jackson-js</a> offers to serialize and deserialize JavaScript objects are: ObjectMapper , JsonStringifier and JsonParser .</p><h4>ObjectMapper</h4><p>ObjectMapper provides functionality for both reading and writing JSON and applies jackson-js <strong>decorators</strong>. It will use instances of JsonParser and JsonStringifier for implementing actual reading/writing of JSON. It has two methods:</p><ul><li>stringify(obj: T, context?: JsonStringifierContext): string: a method for serializing a JavaScript object or a value to a JSON string with <strong>decorators</strong> applied;</li><li>parse(text: string, context?: JsonParserContext): T: a method for deserializing a JSON string into a JavaScript object/value (of type T, based on the context given) with <strong>decorators</strong> applied.</li></ul><h4>JsonParser</h4><p>JsonParser provides functionality for writing JSON and applies jackson-js decorators. The main methods are:</p><ul><li>parse(text: string, context?: JsonParserContext): T : a method for deserializing a JSON string into a JavaScript object/value (of type T, based on the context given) with <strong>decorators</strong> applied;</li><li>transform(value: any, context?: JsonParserContext): any : a method for applying jackson-js <strong>decorators</strong> to a JavaScript object/value parsed. It returns a JavaScript object/value with decorators applied.</li></ul><h4>JsonStringifier</h4><p>JsonStringifier provides functionality for reading JSON and applies jackson-js <strong>decorators</strong>. The main methods are:</p><ul><li>stringify(obj: T, context?: JsonStringifierContext): string: a method for serializing a JavaScript object or a value to a JSON string with <strong>decorators</strong> applied;</li><li>transform(value: any, context?: JsonStringifierContext): any: a method for applying jackson-js <strong>decorators</strong> to a JavaScript object/value. It returns a JavaScript object/value with decorators applied and ready to be JSON serialized.</li></ul><h3>Decorators</h3><p>Before we go on, I need to say that the most important decorators are:</p><ul><li>@JsonProperty() : each class property (or its getter/setter) must be decorated with this decorator, otherwise, deserialization and serialization will not work properly! That’s because, for example, given a JavaScript class, there isn’t any way or API (such as <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/package-summary.html">Reflection API for Java</a>) to get for sure all the class properties; also because, sometimes, compilers such as <a href="https://www.typescriptlang.org/">TypeScript</a> and <a href="https://babeljs.io/">Babel</a>, can strip class properties after compilation from the class properties declaration;</li><li>@JsonClassType() : this decorator, instead, is used to define the type of a class property or method parameter. This information is used during serialization and, more important, during deserialization to know about the <strong>type of a property</strong>/<strong>parameter</strong>. This is necessary because JavaScript isn’t a strongly-typed programming language, so, for example, during deserialization, without the usage of this decorator, there isn’t any way to know the specific type of a class property, such as a Date or a custom Class type.</li></ul><p>Later, they will be explained in more detail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d2437fd1cfe2c0e68e0aca25c0fa7ce/href">https://medium.com/media/4d2437fd1cfe2c0e68e0aca25c0fa7ce/href</a></iframe><h3>@JsonAlias</h3><p>The<em> @JsonAlias</em> decorator defines one or more alternative names for a property during deserialization.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonalias">JsonAlias</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonaliasoptions.html">JsonAliasOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b76788add90ff1d8be7d7a5100fe67ba/href">https://medium.com/media/b76788add90ff1d8be7d7a5100fe67ba/href</a></iframe><h3>@JsonAnyGetter</h3><p>The<em> @JsonAnyGetter</em> decorator allows the flexibility of using a Map or an Object Literal field as standard properties.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonanygetter">JsonAnyGetter</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonanygetteroptions.html">JsonAnyGetterOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/990b565376a401eb8bc6307c174500fb/href">https://medium.com/media/990b565376a401eb8bc6307c174500fb/href</a></iframe><h3>@JsonAnySetter</h3><p><em>@JsonAnySetter</em> allows us to define a logical “any setter” mutator using a non-static two-argument method to be used as a “fallback” handler for all otherwise unrecognized properties found from JSON content.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonanysetter">JsonAnySetter</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/types.html#jsonanysetteroptions">JsonAnySetterOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03fe38d5867f748e261506b1a4aa5985/href">https://medium.com/media/03fe38d5867f748e261506b1a4aa5985/href</a></iframe><h3>@JsonAppend</h3><p><em>@JsonAppend</em> can be used to add “virtual” properties to be written after regular properties.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonappend">JsonAppend</a> — decorator options: <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonappendoptions.html">JsonAppendOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edcf668e70a360255c34c22cef9fa9c6/href">https://medium.com/media/edcf668e70a360255c34c22cef9fa9c6/href</a></iframe><h3>@JsonManagedReference and @JsonBackReference</h3><p>The <em>@JsonManagedReference</em> and <em>@JsonBackReference</em> decorators can handle parent/child relationships and work around loops.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonmanagedreference">JsonManagedReference</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonmanagedreferenceoptions.html">JsonManagedReferenceOptions</a>, <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonbackreference">JsonBackReference</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonbackreferenceoptions.html">JsonBackReferenceOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96b1ca6c4ed6d8721a5bd9f6a3adb43d/href">https://medium.com/media/96b1ca6c4ed6d8721a5bd9f6a3adb43d/href</a></iframe><h3>@JsonClassType</h3><p>As said before, the <em>@JsonClassType</em> is used to define the type of a class property or method parameter. A type is defined as an Array of JavaScript classes, such as [Number] for properties of type number or [Array, [Number]] for properties of type Array&lt;number&gt; or [Map, [String, Object]] for properties of type Map&lt;string, any&gt;.</p><p>Why an Array of JavaScript classes? Because in this way you can map complex types such as Map&lt;string, any&gt; using [Map, [String, Object]] or Array&lt;Set&lt;any&gt;&gt; using [Array, [Set, [Object]]] .</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonclasstype">JsonClassType</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonclasstypeoptions.html">JsonClassTypeOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed0ebc67c248857c54de019c3e8c2fad/href">https://medium.com/media/ed0ebc67c248857c54de019c3e8c2fad/href</a></iframe><h3>@JsonCreator</h3><p>We can use the <em>@JsonCreator</em> decorator to define constructors and factory methods as one to use for instantiating new instances of the associated class.</p><p>It’s very helpful when we need to deserialize some JSON that doesn’t exactly match the target entity we need to get, also with the help of the <em>@JsonProperty</em> decorator.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsoncreator">JsonCreator</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsoncreatoroptions.html">JsonCreatorOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d61b1235a577b9ac626e10fb42db7c5/href">https://medium.com/media/4d61b1235a577b9ac626e10fb42db7c5/href</a></iframe><h3>@JsonSerialize and @JsonDeserialize</h3><p><em>@JsonSerialize</em> and @<em>JsonDeserialize</em> are used to indicates the use of a custom serializer/deserializer.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonserialize">JsonSerialize</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonserializeoptions.html">JsonSerializeOptions</a>, <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsondeserialize">JsonDeserialize</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsondeserializeoptions.html">JsonDeserializeOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24bd4abc8bfd7a4ed64b5bd017470971/href">https://medium.com/media/24bd4abc8bfd7a4ed64b5bd017470971/href</a></iframe><h3>@JsonFilter</h3><p><em>@JsonFilter</em> can be used to indicate which logical filter is to be used for filtering out properties of type (class) decorated.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonfilter">JsonFilter</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonfilteroptions.html">JsonFilterOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0230375bdee28c978b8d1b7a3292c7d/href">https://medium.com/media/b0230375bdee28c978b8d1b7a3292c7d/href</a></iframe><h3>@JsonFormat</h3><p><em>@JsonFormat</em> is a general-purpose decorator used for configuring details of how values of properties are to be serialized.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonformat">JsonFormat</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/types.html#jsonformatoptions">JsonFormatOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/950b3bdcd39de64f03f37311a5fff34d/href">https://medium.com/media/950b3bdcd39de64f03f37311a5fff34d/href</a></iframe><h3>@JsonGetter and @JsonSetter</h3><p><em>@JsonGetter</em> and <em>@JsonSetter</em> are alternatives to more general <em>@JsonProperty</em> decorator to mark a method as a getter/setter method for a logical property.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsongetter">JsonGetter</a> — decorator options: <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsongetteroptions.html">JsonGetterOptions</a>, <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonsetter">JsonSetter</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonsetteroptions.html">JsonSetterOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d804c1b6eb00377b90bfbceca047862/href">https://medium.com/media/2d804c1b6eb00377b90bfbceca047862/href</a></iframe><h3>@JsonIdentityInfo</h3><p><em>@JsonIdentityInfo</em> indicates that Object Identity should be used when serializing/deserializing values — for instance, to deal with infinite recursion type of problems.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonidentityinfo">JsonIdentityInfo</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonidentityinfooptions.html">JsonIdentityInfoOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52d745037b6a1cc7964e4061989ec2b9/href">https://medium.com/media/52d745037b6a1cc7964e4061989ec2b9/href</a></iframe><h3>@JsonIdentityReference</h3><p><em>@JsonIdentityReference</em> can be used for customizing details of a reference to Objects for which “Object Identity” is enabled (see <em>@JsonIdentityInfo</em>). The main use case is that of enforcing the use of Object Id even for the first time an Object is referenced, instead of the first instance being serialized as full Class.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonidentityreference">JsonIdentityReference</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonidentityreferenceoptions.html">JsonIdentityReferenceOptions</a>.</p><h3>@JsonIgnore, @JsonIgnoreProperties, and @JsonIgnoreType</h3><p><em>@JsonIgnore</em> is used to mark a property to be ignored at the field level during serialization and deserialization.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonignore">JsonIgnore</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/types.html#jsonignoreoptions">JsonIgnoreOptions</a>.</p><p><em>@JsonIgnoreProperties</em> can be used as a class-level decorator that marks a property or a list of properties that will be ignored during serialization and deserialization.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonignoreproperties">JsonIgnoreProperties</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonignorepropertiesoptions.html">JsonIgnorePropertiesOptions</a>.</p><p><em>@JsonIgnoreType</em> indicates that all properties of decorated type are to be ignored during serialization and deserialization.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonignoretype">JsonIgnoreType</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/types.html#jsonignoretypeoptions">JsonIgnoreTypeOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6d311264cc55cab4e5b46b734846cd8/href">https://medium.com/media/a6d311264cc55cab4e5b46b734846cd8/href</a></iframe><h3>@JsonInclude</h3><p><em>@JsonInclude</em> can be used to exclude properties with empty/null/default values.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsoninclude">JsonInclude</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/types.html#jsonincludeoptions">JsonIncludeOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e88d48be43fbddf8e2c2db80de91e0eb/href">https://medium.com/media/e88d48be43fbddf8e2c2db80de91e0eb/href</a></iframe><h3>@JsonInject</h3><p><em>@JsonInject</em> decorator is used to indicate that value of decorated property will be injected during deserialization.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsoninject">JsonInject</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsoninjectoptions.html">JsonInjectOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9215ed6a8e7d352b7472a1e7935c31b5/href">https://medium.com/media/9215ed6a8e7d352b7472a1e7935c31b5/href</a></iframe><h3>@JsonNaming</h3><p><em>@JsonNaming</em> decorator is used to choose the naming strategies (SNAKE_CASE, UPPER_CAMEL_CASE, LOWER_CAMEL_CASE, LOWER_CASE, KEBAB_CASE, and LOWER_DOT_CASE) for properties in serialization, overriding the default.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonnaming">JsonNaming</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonnamingoptions.html">JsonNamingOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4d745f2ae8b7c92d8a768d39a85d62c/href">https://medium.com/media/c4d745f2ae8b7c92d8a768d39a85d62c/href</a></iframe><h3>@JsonProperty</h3><p><em>@JsonProperty</em> can be used to define a non-static method as a “setter” or “getter” for a logical property or non-static object field to be used (serialized, deserialized) as a logical property.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonproperty">JsonProperty</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonpropertyoptions.html">JsonPropertyOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03dc8c6122a164a63b1fb8b7474d439a/href">https://medium.com/media/03dc8c6122a164a63b1fb8b7474d439a/href</a></iframe><h3>@JsonPropertyOrder</h3><p><em>@JsonPropertyOrder</em> can be used to specify the order of properties on serialization.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonpropertyorder">JsonPropertyOrder</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonpropertyorderoptions.html">JsonPropertyOrderOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52027c8060b96d2167a76b184393402a/href">https://medium.com/media/52027c8060b96d2167a76b184393402a/href</a></iframe><h3>@JsonRawValue</h3><p><em>@JsonRawValue</em> decorator indicates that the decorated method or field should be serialized by including literal String value of the property as is, without quoting of characters. This can be useful for injecting values already serialized in JSON or passing javascript function definitions from server to a javascript client.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonrawvalue">JsonRawValue</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/types.html#jsonrawvalueoptions">JsonRawValueOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03c4c4a3822115adee2f6065b673cbe9/href">https://medium.com/media/03c4c4a3822115adee2f6065b673cbe9/href</a></iframe><h3>@JsonRootName</h3><p><em>@JsonRootName</em> decorator is used — if wrapping is enabled — to specify the name of the root wrapper to be used.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonrootname">JsonRootName</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonrootnameoptions.html">JsonRootNameOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a869839635cdb51dd72f475a34112bd4/href">https://medium.com/media/a869839635cdb51dd72f475a34112bd4/href</a></iframe><h3>Polymorphic Type Handling Decorators: @JsonTypeInfo, @JsonSubTypes, and @JsonTypeName</h3><ul><li><em>@JsonTypeInfo</em>: indicates details of what type information to include in serialization; <strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsontypeinfo">JsonTypeInfo</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsontypeinfooptions.html">JsonTypeInfoOptions</a>;</li><li><em>@JsonSubTypes</em>: indicates sub-types of the annotated type; <strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonsubtypes">JsonSubTypes</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonsubtypesoptions.html">JsonSubTypesOptions</a>;</li><li><em>@JsonTypeName</em>: defines a logical type name to use for annotated class; <strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsontypename">JsonTypeName</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsontypenameoptions.html">JsonTypeNameOptions</a>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b47209bc76c0401920b4a2b7db59bcc/href">https://medium.com/media/2b47209bc76c0401920b4a2b7db59bcc/href</a></iframe><h3>@JsonTypeId</h3><p><em>@JsonTypeId</em> decorator is used to indicate that the annotated property should be serialized as the type id when including polymorphic type information, rather than as a regular property. That polymorphic metadata is used during deserialization to recreate objects of the same subtypes as they were before serialization, rather than of the declared supertypes.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsontypeid">JsonTypeId</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/types.html#jsontypeidoptions">JsonTypeIdOptions</a>.</p><h3>@JsonTypeIdResolver</h3><p><em>@JsonTypeIdResolver</em> decorator can be used to plug a custom type identifier handler to be used for converting between JavaScript types and type id included in JSON content.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsontypeidresolver">JsonTypeIdResolver</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsontypeidresolveroptions.html">JsonTypeIdResolverOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63b4acfd16b1cfe5c02750bbc8023035/href">https://medium.com/media/63b4acfd16b1cfe5c02750bbc8023035/href</a></iframe><h3>@JsonUnwrapped</h3><p><em>@JsonUnwrapped</em> defines values that should be unwrapped/flattened when serialized/deserialized.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonunwrapped">JsonUnwrapped</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonunwrappedoptions.html">JsonUnwrappedOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7033ae0720188955b89a85e2d45f77a5/href">https://medium.com/media/7033ae0720188955b89a85e2d45f77a5/href</a></iframe><h3>@JsonValue</h3><p><em>@JsonValue</em> decorator indicates that the value of decorated accessor (either field or “getter” method) is to be used as the single value to serialize for the instance, instead of the usual method of collecting properties of value.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonvalue">JsonValue</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/types.html#jsonvalueoptions">JsonValueOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dfaed12d09d908ed5a4fc97739b3641/href">https://medium.com/media/3dfaed12d09d908ed5a4fc97739b3641/href</a></iframe><h3>@JsonView</h3><p><em>@JsonView</em> decorator is used for indicating view(s) that the property that is defined by method or field decorated is part of. If multiple View class identifiers are included, the property will be part of all of them. It is also possible to use this decorator on classes to indicate the default view(s) for properties of the type, unless overridden by per-property decorator.</p><p><strong>API</strong>: <a href="https://pichillilorenzo.github.io/jackson-js/latest/modules/decorators.html#jsonview">JsonView</a> — decorator options <a href="https://pichillilorenzo.github.io/jackson-js/latest/interfaces/types.jsonviewoptions.html">JsonViewOptions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df37ab3106484e65c8412974cd872eaf/href">https://medium.com/media/df37ab3106484e65c8412974cd872eaf/href</a></iframe><h3>Conclusion</h3><p>In the next part (“<a href="https://medium.com/@pichillilorenzo/jackson-js-examples-for-client-and-server-side-part-2-7e66df74c851"><em>Jackson-js: Examples for client (Angular) and server (Node.js) side (Part 2)</em></a>”), I will give a simple example using <a href="https://github.com/pichillilorenzo/jackson-js">jackson-js</a> with Angular 9 for the client side and two examples for the server side: one using Node.js + <a href="http://expressjs.com/">Express</a> + SQLite3 (with <a href="https://sequelize.org/">Sequelize 5</a>) and another one using Node.js + <a href="https://github.com/strongloop/loopback-next">LoopBack 4</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df952454cf" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/jackson-js-powerful-javascript-decorators-to-serialize-deserialize-objects-into-json-and-vice-df952454cf">Jackson-js: Powerful JavaScript decorators to serialize/deserialize objects into JSON and vice…</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>