


JSON realizes seven lines of code to turn the website into a mobile application
This article introduces how to use Jasonette to integrate web views and native components to build a true "hybrid" application, turning your website into a mobile application. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
If I told you that you only need the above 7 lines of orange JSON code to turn a website into a mobile application, would you believe it? There is absolutely no need to rewrite the website using some framework API to get the same behavior as a mobile app. If you already have an existing website, you can "package" it as a native app by simply referencing the URL.
On this basis, you only need to slightly adjust the JSON code content, and you can directly access all native APIs, native UI components, and native view transitions (View Transition).
The most simplified example effect is shown below:
As you can see from this, I have embedded a GitHub.com Web page, but the rest of the layout on the interface are native UI components, such as the navigation bar and the tab bar at the bottom. And we don't need to use any API to rewrite the website, we can automatically get the native switching effect.
Before introducing the specific method, you may ask: "It looks cool, but apart from displaying Web pages within the native application framework, what is the significance of this technology?
Ask Great! This is also the focus of this article. We only need to create a seamless two-way communication between the web view and the application, so that the parent application can trigger any JavaScript function within the web view, and then the web view can be accessed from the outside Call the native API.
For example:
Please note that this view contains:
- ##Native navigation bar, and built-in switching function
- A Web view, which embeds a Web application that can generate QR codes
- Include a native text input component at the bottom
- Why the integration of web engines and native components is often a better approach.
- Why seamless integration of HTML and native is so Difficult, and how to implement it.
- More importantly, how to use such technology to quickly build your own applications.
##Why use HTML in native applications?Before going further, let’s first look at whether it is good or bad, and when it is appropriate to use this method. . Some potential use cases for this approach are as follows:
1. Using Web native functionsIt may be more appropriate to use a Web engine to implement some of the content in the application. approach. For example, WebSocket is a native Web function and is mainly designed for the Web environment. In this case, it is more suitable to use the built-in Web engine (iOS's WKWebView and Android's WebView) instead of installing some A third-party library that "emulates" WebSocket.
Wouldn't it be better to use a free tool to achieve your goal without installing any additional code. This also leads to the next reason.
2. Avoid binary files that are too large in size
Some functions may require the help of huge third-party libraries, and you may want to use such functions quickly.
For example , in order to include the QR code image generator natively, you may need to install some third-party libraries, which will cause the binary file size to increase. But if you use the Web view engine and call the JavaScript library through a simple
3. Lack of reliable mobile librariesFor some cutting-edge technologies, it may not be available for the time being. There is no stable and reliable mobile terminal implementation.
Fortunately, most of these technologies have web implementations, so the most efficient integration method is to use JavaScript libraries.
4. Build a part-native, part-web-based application
Many novice developers want to port their websites into mobile applications, but find that they have It’s common to get frustrated or frustrated when parts of your website are too complex to quickly rewrite for each mobile platform.
For example you might have a very complex web page that cannot be quickly converted to a mobile app, but the rest of the site can be converted easily.
Faced with this situation, if most of the content of the application is built in a native way through some method, wouldn't it be very easy to directly integrate particularly complex pages into the application in the form of HTML? Great.
How is this achieved?
A. Jasonette
Jasonette is an open source method for building cross-platform native applications based on markup language.
The technology looks like a web browser, but instead of interpreting HTML markup language into web pages, it interprets JSON markup into native apps on iOS and Android.
Just as all web browsers have the exact same code, but provide users with all different types of web applications by interpreting different types of HTML tags as needed, all Jasonette applications have the exact same libraries , which can interpret different types of JSON tags as needed and create your application. Developers do not need to touch the code itself at all. They only need to write tags and "translate" the code into native applications in real time to develop their own applications.
Although the core role of Jasonette is to build native applications, the focus of this article is to introduce how to integrate HTML into the core native engine. Let’s take a look at it together.
B. Jasonette Web Container
Native applications are great, but sometimes we still need to use web functionality.
But the integration of web views and native applications is a troublesome process. Seamless integration requirements:
Web views should be integrated as part of the native layout: Web views should be included in the app as part of the native layout and operate in the same way as other Any native UI components remain consistent. Otherwise it will feel clunky and make the user feel like they are actually visiting the website.
Parent application can control the child web container: The parent application should be able to control the child web view at will.
The child web container can trigger the parent application's native events: The child application should be able to trigger the parent application's events to run the native API.
This is a lot of work, so let’s start with the first step: embedding the web container directly into the native layout — and publishing it as version 1:
JSON Web container, HTML in JSON will become native application components.
This alone is very practical, but since it cannot interact, there are still certain limitations.
The parent application cannot control the child web container, and the child container cannot send any event notifications to the parent application, which results in the web container being completely isolated from the outside world.
C. Jasonette Web Container 2.0: Making it Interactive
After releasing version 1, we started working on the second problem: adding interactivity to the web container.
The following will introduce how to add interactive capabilities to the previously created static web container to make it more powerful.
Implementation: Interactive Web Container
1. Loading via URL
Question
Previously in version 1, in order to use the web container as the background view component, we first needed to set $jason.body.background.type to "html", and then in $jason.body Add hardcoded HTML text under the .background.text property, for example:
Generally speaking, people tend to prefer to use the Web URL directly to instantiate the container ization rather than having the entire HTML code hard-coded as a single line of code.
Solution
Web container 2.0 added the url attribute, we can embed local HTML in the form of file://, for example (can be published from the local accompanying application HTML file loading):
# Or you can embed the remote http[s]:// URL, for example like this (can load from remote HTML):
2. Two-way communication between parent application and web container
Problem
Before, Web containers can only be used to display content and cannot be interacted with. This means that all of the following are not possible:
Communication from Jasonette to the web container: calling JavaScript functions inside the web container from Jasonette.
Web container to Jasonette communication: calling native APIs from within the web container code.
At this time we can only display the content of the web container. This is like an iframe embedded in a web page, and the content in the iframe is completely inaccessible to the main page.
Solution:
Jasonette's biggest goal is to design a standardized markup language that can describe cross-platform mobile applications. Therefore we need a markup language that can comprehensively describe the two-way communication between the parent application and the child web container.
To do this I use a JSON-RPC based communication pipeline between the parent application and the child web container. Since everything in Jasonette is expressed through JSON objects, using the JSON-RPC standard format as the communication protocol becomes a very natural and reasonable way.
In order for JavaScript functions to call the Web container, an operation named $agent.request needs to be declared:
$agent.request is a native API that triggers JSON-RPC requests and sends them to the web container. In order to use the API, an options object must be passed as a parameter.
The options object is actually a JSON-RPC request sent to the web container. The meaning of each attribute is as follows:
id: The Web container is built on an underlying architecture called Agent. Generally speaking, we can use multiple Agent, each Agent can have its own unique ID. But the web container is a special type of Agent and can only use $webcontainer as the ID, so the ID needs to be used here.
method: The name of the JavaScript function to be called.
params: Array of parameters passed to the JavaScript function.
So in full view, the tags used should be similar to this:
This string of tags is actually Saying:
When the view loads ($jason.head.actions.$load), send a JSON-RPC request ($agent.request) to the Web container Agent, and the specific request is specified through options of.
The Web container is defined under $jason.body.background. In this example, a local file named file://index.html will be loaded.
It will then find a JavaScript function named login and pass the two parameters under params ("alice" and "1234").
The above describes how the parent application triggers the JavaScript function call of the child Web container. We can also do the opposite and let the Web container trigger the native API of the parent application. .
Please refer to the Agent documentation for details.
Agent documentation: https://docs.jasonette.com/agents/
Example
Continue to return to the above introduction QR code generator example:
The text input component at the bottom is 100% native.
QR code is generated by a web container running as a web application.
When the user enters content and presses "Generate", the $agent.request operation in the Web container Agent will be called, and then the JavaScript function "qr" will be called.
For specific examples, please refer to:
https://github.com/Jasonette/Jasonpedia/blob/gh-pages/webcontainer/agent/fn/index.json
3. Script injection
Problem
Sometimes we may need to complete the initial HTML loading in the Web container Finally, the JavaScript code is dynamically injected into the web container.
Suppose we want to build a custom web browser application, we may want to inject our own custom JavaScript into each web view to customize the behavior of the web view, which is somewhat similar to that of a web browser. Extension.
Even if you don’t need to build a web browser, you still need to use script injection when you want to implement custom behavior for URLs whose content is not controlled by us. Native applications and web containers can only communicate through the $agent API, but if the HTML content cannot be changed, the $agent interface can only be added to the web container through dynamic injection.
Solution
As mentioned above, the $jason.body.background web container is also an agent, which means we can use it exactly the same as a normal Agent The $agent.inject method.
4. Processing of URL clicks
In the past, the web container could only handle link click operations in two ways:
Read-only: treat the web container as read-only, ignoring all such as touch or scroll events. At this time all web containers are read-only unless explicitly told to behave like a normal browser, as described below.
Normal browser behavior: Like a normal browser, allowing the user to interact with the page. A declaration is required for this, setting "type": "$default" as the action attribute.
Problem
Both are “All or nothing” solutions.
For "read-only", the web container ignores all user interactions.
For "normal browser behavior", the web container will behave consistent with the browser. After clicking the link, the page will be refreshed to display the link content like a normal web page, but the click cannot be hijacked and other native APIs called.
Solution
By using the new Web container, any action can be attached to the $jason.body.background Web container, and then Handle events like link clicks.
Let’s look at an example:
Here we attach " trigger": "displayBanner", which means that when the user clicks on any link within the Web container, the displayBanner operation will be triggered instead of being handled directly by the Web view.
In addition, if you look at the displayBanner operation, you will find that the variable $jason appears here. In this example, the clicked link will be passed through the $jason variable. For example, if a URL called "https://google.com" is clicked, $jason will get the following value:
This means we can check The value of $jason.url then selectively triggers different actions.
Let’s take a look at the implementation of a custom web browser as another example:
We will check whether the URL contains the string signin , and perform two different operations based on the results.
#If signin is included, open a new view and complete the login operation natively.
If signin is not included, the "type": "$default" operation will be run directly to achieve behavior similar to that of an ordinary browser.
Usage demonstration
Build a custom web browser
Many interesting operations can be achieved by taking advantage of the following features of the new version of the Web container:
Realizes self-loading through the url attribute and acts as a full-featured browser.
Selectively handle link click operations based on different URLs.
We can even build a custom web browser with dozens of lines of JSON code. Since every link click can now be hijacked, we can check $jason.url and run whatever actions we need based on the results.
For example, the following example:
Build "hybrid" applications in an instant
When people usually talk about "hybrid" applications, they mainly refer to HTML web applications encapsulated within a native application framework.
But this is not the application mentioned here. The so-called "hybrid" here refers to a true hybrid application, that is, an application that can contain multiple native views and multiple web-based views at the same time. In this kind of application, a view can have multiple native UI components, and a web container rendered with the same native layout.
The interweaving of web views and native views should be as seamless as possible, making it completely indistinguishable to users.
#In this example, I created an app that displays content from jasonbase.com in a web container and uses it as a home page view.
Jasonbase is a free JSON hosting service I developed that makes it easy to host the JSON markup used by Jasonette applications.
Of course, this is a website in its own right, but I embedded it into Jasonette so that instead of opening the web page after clicking the link, it will display the native JASON view through native $href conversion.
You can build this application without touching any Jasonbase.com code.
You only need to embed the website into Jasonette as a web container, and then hijack the native processing of link click operations, so that you can realize various functions of native applications, such as triggering native APIs and performing native conversions.
The complete code can be found here: https://github.com/Jasonette/Jasonpedia/blob/gh-pages/webcontainer/agent/hybrid.json
Conclusion
In my opinion, what makes this so awesome is that everything is handled well at the framework level. All the hardest work is done behind the scenes.
App developers do not need to waste time and effort to implement the following from scratch:
Embed the web view into the native layout
Create a JavaScript bridge so that the application can call functions in the web view
Create a native event handling architecture so that the web view can trigger native events of the parent application
The entire solution creates an abstraction consisting of:
Declarative markup language: used to describe how to embed a Web view Native application.
Communication Protocol (JSON-RPC): For extremely simple communication between the application and its child web views.
I don’t think this method can solve all problems, but judging from my own use cases, it is a good solution to say the least.
I try to build applications with very cutting-edge technologies, which are so cutting-edge that there is no stable and reliable implementation on the mobile side (due to some nature of the protocol, it is not even clear whether there will be a mobile version in the end) accomplish). Fortunately, these technologies are implemented in JavaScript, so integrating them into your application is easy and effortless.
Overall, this technique is great and I'm very happy with the results so far. The latest version of the documentation already contains all new features, and everyone is welcome to study it in depth and try it out.
Statement: The greater the ability, the greater the responsibility you need to bear
Finally, I want to say: Although this new technology is indeed very powerful, I think everyone When developing applications, more comprehensive trade-offs should be made in terms of user experience.
Some people may use this technology to build an application entirely composed of Web views, but in the final analysis, your application is actually just a website, which is contrary to the original intention of developing a dedicated application.
It’s important to stress that I don’t think every app you have should contain both HTML and native components. I just think that this approach will be more useful for many people facing certain specific situations, just don't go overboard.
Summary: The above is the entire content of this article. The code is very simple, you can try it. I hope it will be helpful to everyone's learning. For more related tutorials, please visit JavaScript Video Tutorial, jQuery Video Tutorial, bootstrap Tutorial!
The above is the detailed content of JSON realizes seven lines of code to turn the website into a mobile application. For more information, please follow other related articles on the PHP Chinese website!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use