Wechat official number: [Cat twelve daily], welcome to leave a message and point out the problem, deep drift in the front of the tuanzi, cat twelve shovel shit officer, life not only code, but also cats and you.

Introduction to the

In the electron, we can use all the built-in NodeJs module, including third party NPM package, it also provides for the development of native desktop applications provides an extra built-in module, some modules can only be used in the main process, some modules can only be used in the rendering process (web page), some are in the two processes can be used.

Basic rule: This module should only be used in the main process as long as it involves GUI or low-level related processes. The concepts of the main process and the renderer are described in the previous article

Now we will try and learn the API provided by the official website one by one

Process the process

  • Scope of application: Main, Renderer
  • Function: Used to handle extensions of objects

Electron’s Process object inherits Node’s process and adds the following events, properties, and methods, but in a sandboxed rendering process, the process object contains only a subset of the API

The loaded ‘events’

Triggered when Electron loads its internal initialization script and is about to start loading the web page or main script. While we’re not integrating Node with the renderer, we can also use this method to inject some node methods globally (I put all the code together, so I can’t read the github of AymFX)

//main.js
const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");
app.whenReady().then(() = > {
  let win = new BrowserWindow({
    width: 1920.height: 1080.webPreferences: {
      preload: path.resolve(__dirname, "./preload.js"), // Preload String (Optional) - Preloads the specified script before the page runs other scripts. This script can access all Node API scripts regardless of whether the page is integrated with Node. The script path is the absolute path of the file. When Node Integration is closed, the preloaded script reintroduces node's global reference flag from global scope
      // nodeIntegration: true,
      devTools: true.contextIsolation: false.enableRemoteModule: true./ / enable remote
      webviewTag: true.// You need to set up the webView to enable this}});const contents = win.webContents;
  contents.openDevTools(); // Open the debugging tool
  win.loadFile("index.html");
});
//preload.js
const _setImmediate = setImmediate;
const _clearImmediate = clearImmediate;
process.once("loaded".() = > {
  window.setImmediate = _setImmediate;
  window.clearImmediate = _clearImmediate;
  console.log(global."Loaded");
});
console.log(global."Loaded");

// renderer.js
console.log(window.setImmediate);
console.log("Start");
setImmediate(() = > {
  console.log("The end");
});
console.log("Middle");

Copy the code

The results of

We need to inject preload.js in that area when we create the Win window. It seems that we can’t use a relative path or it won’t load

preload: path.resolve(__dirname, "./preload.js")
Copy the code

With this we can inject some Node methods on the web page for us to call up

attribute

  • console.log(“show:”, process.defaultApp);

Read-only Boolean => As a default when the App is started, the main process prints true and the render process prints undefined

  • console.log(“show:”, process.isMainFrame);

Read-only Boolean => When the context of the renderer is the main renderer, use webFrame.routingId if the id of the current frame is needed

  • console.log(“show:”, process.mas);

Read-only Boolean => To build with Mac Apple Store, this property is true, otherwise false

  • console.log(“show:”, process.noAsar);

Setting it to true disables support for ASAR archives in Node’s built-in modules

  • console.log(“show:”, process.noDeprecation);

Used to control whether deprecation warnings are printed to stder. Setting it to true will disable deprecation warnings. Use this property instead of the -no-deprecation command-line flag.

  • console.log(“show:”, process.resourcesPath);

Read-only Boolean => Returns the current resource path

  • console.log(“show:”, process.sandboxed);

Read-only Boolean => true in the renderer process, false otherwise

  • console.log(“show:”, process.throwDeprecation);

Used to control whether deprecation warnings are treated as exceptions. Setting it to true throws an error. Use this property instead of the –throw-deprecation command-line flag.

  • console.log(“show:”, process.traceDeprecation);

Used to control whether its stack trace is included in deprecations printed to stderr. Setting this to true will print the deprecated stack trace. This property replaces the –trace-deprecation command line flag.

  • console.log(“show:”, process.traceProcessWarnings);

A Boolean that controls whether a process warning is printed to the stderr containing the stack trace. Setting this to true prints a stack trace of process warnings (including deprecation). This property replaces the –trace-warnings command line flag.

  • console.log(“show:”, process.type); read-onlystringtype
    • Browser main process
    • Renderer Process
    • worker web woreker
  • console.log(“show:”, process.versions.chrome);

Read-only Boolean value => String, a string representing the Chrome version.

  • console.log(“show:”, process.versions.electron);

Read-only Boolean value =>string, a string representing the Electron version.

  • console.log(“show:”, process.windowsStore);

Read-only Boolean value => Whether it runs on the Window Store app

Main.js printed out

show: true
show: undefined
show: undefined
show: undefined
show: undefined
show: /Users/aymfx/gitRepository/electron-examples/2020-01-18/node_modules/_electron@11.2. 0@electron/dist/Electron.app/Contents/Resources
show: undefined
show: undefined
show: undefined
show: undefined
show: browser
show: 87.04280.141.
show: 11.2. 0
show:
Copy the code

Renderer.js is printed out

renderer.js:8 show: undefined
renderer.js:9 show: true
renderer.js:10 show: undefined
renderer.js:11 show: undefined
renderer.js:12 show: undefined
renderer.js:13 show: /Users/aymfx/gitRepository/electron-examples/2020-01-18/node_modules/_electron@11.2. 0@electron/dist/Electron.app/Contents/Resources
renderer.js:13
renderer.js:15 show: undefined
renderer.js:16 show: undefined
renderer.js:17 show: undefined
renderer.js:18 show: undefined
renderer.js:19 show: renderer
renderer.js:20 show: 87.04280.141.
renderer.js:21 show: 11.2. 0
renderer.js:21 show: undefined
Copy the code

methods

process.crash()

The main thread that causes the current process to crash. Straight down the app

! [image-20210120115212278](/Users/liuyang/Library/Application Support/typora-user-images/image-20210120115212278.png)

process.getCreationTime()

Returns Number | null – starting from the era of the Number of milliseconds, if the information is not available it returns null

Represents the creation time of the application, or null if the creation time stream cannot be retrieved

  console.log(process.getCreationTime()); / / 1611114906194.985
Copy the code

process.getIOCounters()

This value returns the number of I/OS, only for Windows and Linux platforms

process.getHeapStatistics()

Returns v8 heap data

  console.log(process.getHeapStatistics());
  /** { totalHeapSize: 4488, totalHeapSizeExecutable: 608, totalPhysicalSize: 3849, totalAvailableSize: 4190654, usedHeapSize: 3104, heapSizeLimit: 4194048, mallocedMemory: 128, peakMallocedMemory: 711, doesZapGarbage: false } */
Copy the code

process.getBlinkMemoryInfo()

Returns an object with flashing memory information. This can be useful for debugging memory issues related to rendering/DOM. Note that all values are reported in kilobytes

  console.log(process.getBlinkMemoryInfo() ); //{ allocated: 0, total: 0 }
Copy the code

process.getProcessMemoryInfo()

Returns an object that provides memory usage statistics for the current process,Chromium does not provide the residentSet value for macOS. This is because macOS performs memory compression on recently unused pages, and private memory is more representative of the actual pre-compression memory usage of processes on macOS.

  process.getProcessMemoryInfo().then((res) = > {
    console.log(res); //{ private: 62572, shared: 32 }
  });
Copy the code

process.getSystemMemoryInfo()

Returns the Object:

  • totalInteger – Total physical memory available to the system (Kb).
  • freeInteger – The total amount of unused memory for the application or disk cache.
  • swapTotal Integer Windows Linux– System swap memory capacity (in kilobytes).
  • swapFree Integer Windows Linux– Available swap memory size of the system (in kilobytes).
 console.log(process.getSystemMemoryInfo()); //{ total: 16777216, free: 14788 }
Copy the code

process.getSystemVersion()

  console.log(process.getSystemVersion()); / / 11.1.0
Copy the code

process.takeHeapSnapshot(pathName)

Returns a Boolean value indicating whether a snapshot was successfully created. A file snapshot is generated

console.log(process.takeHeapSnapshot("index.js")); //true
Copy the code

process.hang()

The main thread that causes the current process to hang.

  console.log(process.hang()); // The page is not displayed
Copy the code

process.setFdLimit(maxDescriptors)

  • maxDescriptors Integer

Set the soft limit for file descriptors to either maxDescriptors or OS hard limit, whichever is the lower value of the current process.

Supports command line switch

Electron supports command line switch, you can come into force in app module ready event, before using the app.com mandLine. AppendSwitch attach them to your application’s main script

–auth-server-whitelist=url

Comma-separated list of servers with integrated authentication enabled.

Some nodejs commands can also be added at the end

Specific documentation supports command-line switches

The environment variable

Some of Electrond’s behavior is controlled by environment variables because they are initialized earlier than command line flags and the application’s code, controlling the application’s behavior without changing the code

Posix shell sample

export ELECTRON_ENABLE_LOGGING=true
Copy the code

Win the console

set ELECTRON_ENABLE_LOGGING=true
Copy the code

Specific document environment variables

The File object

On the File system, files are manipulated using HTML5’s File, and Electron has added a path attribute to the File interface, exposing a real path to the File system

Index.html

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Electron demo</title>
</head>

<body>Electron demo<div id="holder">
        Drag your file here
        <img src="" class="img" />
    </div>
    <script src="./renderer.js"></script>
</body>
</html>
Copy the code

renderer.js

document.addEventListener("drop".(e) = > {
  e.preventDefault();
  e.stopPropagation();

  for (const f of e.dataTransfer.files) {
    let img = document.querySelector(".img");
    console.log("File(s) you dragged here: ", f.path); img.src = f.path; }});document.addEventListener("dragover".(e) = > {
  e.preventDefault();
  e.stopPropagation();
});
Copy the code

Finally drag the photo effect

If you think my article is ok, click a like or follow the next, there are wonderful stories waiting for you oh, but also can cloud masturbation cat