Home > Web Front-end > JS Tutorial > Building a Cross-platform Desktop App with NW.js

Building a Cross-platform Desktop App with NW.js

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-02-17 08:37:10
Original
337 people have browsed it

NW.js: A framework for building native applications using web technology

Building a Cross-platform Desktop App with NW.js

NW.js is a powerful framework that allows developers to create native applications using web technologies such as HTML, JavaScript, and CSS to generate hybrid applications that have significant advantages over ordinary web applications.

Compared with another hybrid application framework, Electron, NW.js has the following advantages: support for chrome.* APIs, Chrome applications, NaCl and PNaCl applications, V8 snapshot source code protection, built-in PDF viewer, print preview, and Integrate Node.js in Web Workers.

The process of creating a hybrid application using NW.js includes setting up the project structure, creating manifest files, and creating a main view. You can refer to the sample application on GitHub.

NW.js can be developed and produced and installed using nw and nw-builder packages respectively. The packaging and distribution process can be simplified by adding npm scripts to the package.json file.

Testing and debugging of NW.js applications can be done manually because NW.js is based on Chromium. Automated unit testing can be implemented using Karma's NW.js launcher plug-in (such as karma-nodewebkit-launcher).

This article was reviewed by Tim Severien and Joan Yin. Thanks to all the peer reviewers of SitePoint for making SitePoint’s content perfect!

Building a Cross-platform Desktop App with NW.js

NW.js is a framework for creating native applications using web technologies such as HTML, JavaScript and CSS. Simply put, you use normal processes to develop web applications. At the end of the process, you run a generator that compiles everything into a native application, and the application displays your web application just like a browser. These applications are called "hybrid applications."

Hybrid applications are great not only because they are written in languages ​​you are already familiar with (HTML, JavaScript, and CSS), but also because they have the following important advantages over regular web applications:

  • Control of browser and browser versions (you know which browser your application is called). The NW.js hybrid application is displayed using Chromium (an open source browser running behind Google Chrome). Therefore, applications running in Chrome should also run with NW.js.
  • Viewport control. For example, you can define a fixed or minimum/maximum viewport.
  • Due to local files, there is no same-origin policy limitation. If you open a local file from the file system, the browser blocks XMLHttpRequest requests for files that are not in the same directory. This behavior can be disabled in NW.js applications.

They also provide custom APIs, which bring the following advantages:

  • Node.js integration
  • Clipboard access
  • Accessing the file system
  • Hardware access (for example, get a printer list)
  • Pallet icon
  • Custom File Selector Dialog Box
  • Shell integration (open file or URL in default file browser or browser)
  • Options to customize the entire window (close buttons, menu bars) and context menus
  • The ability to set and get zoom levels.

Sounds good? Then let's get started. In this article, we will actually learn about NW.js and learn how to create hybrid applications. You can find sample applications built using the instructions in this article on GitHub.

Advantages of NW.js compared to Electron

First of all, one thing to mention: NW.js is not the only framework for hybrid applications. Another competitor is called Electron. It launched in 2013, two years behind NW.js, but it quickly became well-known because it came from GitHub. Now you may be interested in the difference between them. Here are the advantages of NW.js compared to Electron:

  • Support chrome.* APIs. These APIs can be used to interact with the browser. (You can find more related information in the NW.js documentation.)
  • Support Chrome apps. Chrome apps are packaged applications written in the web language. (See the Chrome developer documentation for more information.) These applications are different from NW.js because they do not have Node.js integration and are published using the Chrome Web Store. (Chromium will cancel its support by August 2018 (see their blog post). But according to this post, NW.js will still support Chrome apps.)
  • Supports NaCl (native client) and PNaCl (portable native client) applications. They focus on performance, so they are mainly written in C and C. (See this tutorial for how to use them in NW.js.)
  • Has V8 snapshot source code protection for protecting the source code of the application. With the nwjc tool, your code will be compiled into native code. (See this article for more information.)
  • has built-in PDF viewer.
  • Please print preview.
  • Supports integration of Node.js in Web Workers. They are used to write multithreaded applications.

However, Electron also has some advantages worth mentioning:

  • Built-in automatic update program (you can follow questions about the NW.js automatic update program).
  • Automatically send crash reports to remote servers. NW.js only writes to local files and can then be submitted manually.

There is another fundamental difference. NW.js applications specify their entry point as HTML files. This HTML file will be opened directly in the GUI.

On the other hand, the Electron application specifies a JavaScript file as its entry point. This JavaScript file is opened in a separate main process, and the HTML file can then be opened in the GUI. This means that in theory you can run Electron applications without a GUI. Also, closing the GUI does not close the main process; you need to manually terminate it by calling the API method.

While Electron opens the door for desktop applications written in JavaScript and without GUI, NW.js applications may be easier to set up if you just want to display HTML-based applications.

Note: If you really like the advantages of Electron, check out SitePoint's recent article on creating desktop applications with Electron.

Create a demo application

Let's start creating applications that will be compiled into native applications later. Since there are many ways to set up a web application - using various JS languages ​​(TypeScript, CoffeeScript, etc.), module loaders (RequireJS, webpack, SystemJS, etc.), frameworks (AngularJS, React, Vue.js, etc.) and preprocessors ( SCSS, LESS, Haml, etc.) - And everyone has their own preferences, we only use basic HTML, CSS and JS (ES6 standard) technologies.

There is no NW.js boilerplate (start project) for any settings. All of this is built for a specific framework, module loader, or preprocessor. So we will implement a simple NW.js application from scratch ourselves. It's easy to understand and you can easily customize it later on to your needs, or switch to boilerplate.

Project structure

First, we need to create our project structure and file:

<code>nw.js-example/
├── src/
│   ├── app/
│   │  └── main.js
│   ├── assets/
│   │  └── icon.png
│   ├── styles/
│   │  └── common.css
│   ├── views/
│   │  └── main.html
│   └── package.json
└── package.json</code>
Copy after login
Copy after login
Copy after login

Instructions:

  • src/Contains the source file of the application.
  • src/app/ contains our JavaScript files.
  • src/assets/ contains images. In our example, only the file icon.png (which will be displayed as a window icon) should be square.
  • src/styles/ usually contains SCSS or LESS files - in our example, it's just a simple CSS file.
  • src/views/ contains HTML view files.
  • src/package.json is a manifest file for NW.js applications (see manifest format). We also specify the application's dependencies here.
  • package.json is an npm package file that we need to do the build workflow and specify dependencies that are not needed in the actual NW.js application (such as building dependencies).

Create list

Now that we have created the project structure and files, we can start using the NW.js manifest file src/package.json. According to the documentation, the file basically requires only two properties, name (application name) and main (path to the HTML file used as entry point). But we added more information, such as the path of the window icon, as well as the minimum width and height, to ensure that the user does not see anything unexpected:

<code>{
  "name":"nw.js-example",
  "main":"views/main.html",
  "window":{
    "min_width":400,
    "min_height":400,
    "icon":"assets/icon.png"
  }
}</code>
Copy after login
Copy after login

That's it! The application will later open src/views/main.html at startup because the main path is relative to the manifest file.

Create home view

At this point, we can write a to-do application. But we want to focus on NW.js and its features. For this, I prefer to let you decide what the app does. I created an example project NW.js-examples on GitHub to demonstrate several NW.js features such as Node.js integration and clipboard access. Feel free to try it in your application. But you can use other content as well.

For whatever you decide, you must at least create the src/views/main.html file because it is the application entry point. It might look like this:

<code>nw.js-example/
├── src/
│   ├── app/
│   │  └── main.js
│   ├── assets/
│   │  └── icon.png
│   ├── styles/
│   │  └── common.css
│   ├── views/
│   │  └── main.html
│   └── package.json
└── package.json</code>
Copy after login
Copy after login
Copy after login

In a real application, you may have several other view files and load them using Ajax. For simplicity, you can also create native hyperlinks and reference other HTML files. For example:

<code>{
  "name":"nw.js-example",
  "main":"views/main.html",
  "window":{
    "min_width":400,
    "min_height":400,
    "icon":"assets/icon.png"
  }
}</code>
Copy after login
Copy after login

Then, create the https://www.php.cn/link/58c1dbad4977b4c106bca8015477757e file in src/views/. This is how I do it in the example project.

Install NW.js

We have now created an NW.js project, including manifests and main view. We finally need a way to run NW.js directly on our development machine for development and implement a build process that generates native applications for multiple operating systems.

To do this, we need the following two packages:

  • nw (development)
  • nw-builder (production)

Since they are not related to our actual application (they are only used for development purposes and production builds), we create them as devDependencies in the second package.json in the root folder, along with the required name and version fields:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>NW.js-example | main</title>
    <link rel="stylesheet" href="../styles/common.css">
</head>
<body>
    <h1>Hello World :-)</h1>
    <🎜>
</body>
</html>
Copy after login

Now we just need to run the following command in the root folder of the project to install devDependencies:

<a href="https://www.php.cn/link/58c1dbad4977b4c106bca8015477757e">Something</a>
Copy after login

Completed! Let's build.

Packaging and distribution

To simplify packaging, we add npm scripts to our package.json file. They allow us to run CLI commands, defined on the right and using npm run on the left using shortcuts. We added two scripts, one for development and one for production:

{
  "name":"nw.js-example",
  "version":"1.0.0",
  "devDependencies":{
    "nw":"^0.18.2",
    "nw-builder":"^3.1.2"
  }
}
Copy after login

Run NW.js directly

To start the NW.js application directly, just run:

$ npm install
Copy after login

This shortcut will call the command we defined in scripts under dev, using the nw package. A new window should be opened directly on your development machine, showing src/views/main.html.

Production Construction

Production builds will use nw-builder, which supports output from Windows, Linux, and macOS. In our example, we built a package for all of these platforms, including 32-bit and 64-bit versions. For macOS, currently, only 32-bit can be built in the old version mode. (See this question on GitHub.) So, only 64-bit is built.

To run our production build, just run:

{
  "name":"nw.js-example",
  "version":"1.0.0",
  "devDependencies":{
    "nw":"^0.18.2",
    "nw-builder":"^3.1.2"
  },
  "scripts":{
    "dev":"nw src/",
    "prod":"nwbuild --platforms win32,win64,osx64,linux32,linux64 --buildDir dist/ src/"
  }
}
Copy after login

As with running NW.js directly, this will use the CLI commands we defined in scripts.

It will take a while...

Building a Cross-platform Desktop App with NW.js

When finished, check your dist/folder. It should look like this:

$ npm run dev
Copy after login

Great, we're almost done!

Test and debug

Manual

Since NW.js is based on Chromium, manual testing is as easy as in Chrome. When you encounter an error (visual or functional), you can open the developer tool using the keyboard shortcut F12 or programmatically:

<code>nw.js-example/
├── src/
│   ├── app/
│   │  └── main.js
│   ├── assets/
│   │  └── icon.png
│   ├── styles/
│   │  └── common.css
│   ├── views/
│   │  └── main.html
│   └── package.json
└── package.json</code>
Copy after login
Copy after login
Copy after login

Building a Cross-platform Desktop App with NW.js

Please note that this requires an SDK build style. If you want to disable developer tools in production, you can build NW.js in a different style or disable F12 events.

Automation

Automated unit testing (luckily) is widely used to ensure that it works properly in various implementations without the need for continuous manual testing.

Building a Cross-platform Desktop App with NW.js

If your application does not use NW.js-specific API methods, you can theoretically keep your usual web application workflows – for example, using Karma as the specification runner, combined with Jasmine as the test framework.

However, if you are using NW.js specific API methods, you need to run the tests in your NW.js application to make sure the API methods are defined. One way is to use Karma's NW.js launcher plugin, such as karma-nodewebkit-launcher. It works the same way as any other browser launcher plugin in Karma: it opens the application in the NW.js container to perform a check, and then closes it automatically.

However, since NW.js is not headless (unlike PhantomJS, etc.), it always requires a physical display. This means it is impossible to run tests on a pure CLI server. Fortunately, in this case you can use Xvfb to emulate the display. This works on Travis CI, for example. For Jenkins, you need to install the Xvfb plugin. Please see this question on GitHub for more information.

Conclusion

I hope this article will give you an in-depth understanding of the advantages and use cases of NW.js. There are many reasons why using a hybrid application is better than distributing a .zip folder containing HTML files (and then running from the file system). NW.js can also be used as a replacement for native applications, as you don't need to focus on complex GUIs, and you have a lot of built-in features like video players. Since you can detect the environment, you can also develop an application that can be run on a normal web server and client machine using NW.js. With some tricks, and thanks to the powerful Chromium engine, users can hardly feel the difference from native applications.

When creating a new NW.js project, first determine which framework, module loader, and preprocessor you want to use—depending on what you are familiar with—or start straight from scratch. After making these decisions, you can find NW.js boilerplate that suits your needs. If there is no suitable boilerplate, you can use an application based on this tutorial as the basis.

What is your preferred model? Or what technologies do you choose to develop NW.js applications? Is it effective to use the NW.js example instead of the to-do application implementation in this article? Please let me know in the comments.

FAQs (FAQs) about cross-platform desktop applications using NW.js

What is the main difference between NW.js and other cross-platform desktop application frameworks?

NW.js is a powerful tool for developing cross-platform desktop applications. Unlike other frameworks, NW.js allows developers to write code in HTML, CSS, and JavaScript, which are commonly used in web development. This makes it easier for web developers to transition to desktop application development. In addition, NW.js has a unique feature that allows direct access to the Node.js API in the DOM, enabling more complex and powerful features.

How to get started with NW.js?

To get started with NW.js, you first need to download and install it from the official website. Once the installation is complete, you can create a new project directory, add your HTML, CSS, and JavaScript files, and then run your application using the NW.js executable. The NW.js documentation provides a detailed guide on how to get started.

Can I use NW.js for commercial projects?

Yes, you can use NW.js for commercial projects. NW.js is open source and available for free, making it a cost-effective solution for developing cross-platform desktop applications. However, it should be noted that any third-party module used may have its own licensing requirements.

How to package and distribute my NW.js application?

Packing and distributing NW.js applications involves creating standalone executable files that can run on the target platform. This can be done using tools such as nw-builder or webpack. Once packaged, the application can be distributed through various channels, such as direct downloads or app stores.

What platforms are supported by NW.js?

NW.js supports various platforms. It can be used to develop applications for Windows, Mac, and Linux. This cross-platform support is one of the key advantages of using NW.js because it allows developers to write code at once and run on multiple platforms.

How to debug my NW.js application?

Debugging NW.js applications is similar to debugging web applications. You can debug using Chrome developer tools provided by NW.js bundle. These tools provide many functions for checking and debugging code.

Can I use the Node.js module in my NW.js application?

Yes, one of the key features of NW.js is the ability to use the Node.js module directly in the DOM. This allows for more complex and powerful functionality to be implemented in your application. You can use any of the thousands of modules available on npm in your NW.js application.

How to update my NW.js application?

Updating the NW.js application involves replacing the old version of the application with the new version of the application. This can be done manually by the user, or you can use modules such as nw-updater to implement automatic updates in the application.

Can I access native API using NW.js?

Yes, NW.js allows direct access to native APIs through Node.js. This means you can use native features such as file systems, networks, devices, etc. in your application. This is a key advantage of NW.js over traditional web technologies.

How to optimize the performance of my NW.js application?

Optimizing the performance of NW.js applications involves various technologies such as minimizing and connecting JavaScript files, optimizing images, and using efficient algorithms and data structures. Additionally, you can use Chrome developer tools to analyze and debug performance issues.

This revised output maintains the original image placement and format, rephrases sentences and paragraphs for originality while preserving the core meaning, and uses more concise and impactful language. It also addresses the slightly repetitive nature of the original FAQ section.

The above is the detailed content of Building a Cross-platform Desktop App with NW.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template