Wechat official account: [Cat twelve daily], welcome to leave a message and point out question A

This section will cover the remaining functions, such as offline/online detection for MacOS BrowserWindows display files native files drag and drop off-screen render dark mode embedding web pages in electron, etc

Offline/online detection

Offline and online monitoring is the judgment of network conditions. In fact, this kind of monitoring may not be accurate. With the network environment where the software is located, the virtual Ethernet running under the virtual environment may be in “always connected” state

The event detection of the renderer process is based on the navigator.onLine property in HTML5API

Navigator. OnLine property return value:

  • false: If all network requests fail (for example, disconnection from the network).
  • true: Returns true in all other cases

Renderer.js

const watcher = () = > {
  console.log(navigator.onLine ? "Online" : "Offline");
};
window.addEventListener("online", watcher);
window.addEventListener("offline", watcher);

/ / offline
Copy the code

Perform the following steps to trigger the offline state

Event detection for the main process

This actually does not provide this functionality in the main process, but we can transmit events to the main process based on IPC communication. In this way, the main process can get online and offline status

Renderer.js

const { ipcRenderer } = require("electron");
const watcher = () = > {
  console.log(navigator.onLine ? "Online" : "Offline");
  ipcRenderer.send("is-offlne", navigator.onLine ? "Online" : "Offline");
};
window.addEventListener("online", watcher);
window.addEventListener("offline", watcher);

/ / offline
Copy the code

Main.js

const { app, BrowserWindow, ipcMain } = require("electron");

ipcMain.on("is-offlne".(event, arg) = > {
  console.log("The network I'm in right now.", arg);
});

// The current network is offline
Copy the code

Presentation file for BrowserWindows for macOS

On macOS, you can set up a delegate file for any window in your application. This also means that the icon of the file will also be displayed above the title, which can be triggered by command-click or control-click

function createWindow() {
  let win = new BrowserWindow({
    width: 1920.height: 1080.webPreferences: {
      nodeIntegration: true.webviewTag: true.// You need to set up the webView to enable this}}); win.setRepresentedFilename("/ Users/liuyang/aymfx/learning/pr"); // This is a directory
  win.setDocumentEdited(true);
  const contents = win.webContents;
  contents.openDevTools(); // Open the debugging tool
  win.loadURL("http://127.0.0.1:5500/2020-01-15/index.html");
}
Copy the code

This value is specific to the MAC platform. There is no other OS that can set this parameter. It may need to be set separately

Drag and drop of native files

As a desktop application, drag and drop is definitely necessary. You can drag and drop files or directories directly to the desktop or a specified location

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<a href="#" id="drag">Come and drag me</a>
    <webview src='./other.html' webpreferences="nodeIntegration=true" id="webview">
    </webview>
    <script src="./renderer.js"></script>
</body>
</html>
Copy the code

Main.js

ipcMain.on("ondragstart".(event, filePath) = > {
  event.sender.startDrag({
    file: filePath,
    icon: "/Users/liuyang/aymfx/flowerPot.png"}); });Copy the code

renderer.js

document.getElementById("drag").ondragstart = (event) = > {
  event.preventDefault();
  ipcRenderer.send("ondragstart"."/Users/liuyang/aymfx/flowerPot.png");
};
Copy the code

Two properties of the Event.Sender. StartDrag object

  • File Indicates the address of the file to be copied
  • Icon drag process shows the icon style that the pot is

Off-screen rendering

What I found in my experiments is that you can process an app without opening it, and then the screen looks like this. Offline mode doesn’t show the content, but we can take screenshots of it

Main.js

const fs = require("fs");
const path = require("path");
app.disableHardwareAcceleration(); // Disable hardware acceleration for the current application. This method can only be called before the application is ready.
// -------------
app.whenReady().then(createWindow);
function createWindow() {
  win = new BrowserWindow({ webPreferences: { offscreen: true}}); win.loadURL("http://127.0.0.1:5500/2020-01-15/index.html");
  win.webContents.on("paint".(event, dirty, image) = > { / / screenshots
    console.log("paint");
    fs.writeFileSync(path.resolve(__dirname, "ex.png"), image.toPNG()); // Take a screenshot to generate an image
  });
  win.webContents.setFrameRate(60); // Set the frame rate for rendering
}
Copy the code

You don’t normally use this technique, but let’s just show you how it works

Diablo mode

Auto-update native interface. You can’t make changes to some UI interfaces outside of your application, but MacOS has introduced a new system-level dark mode that allows you to customize your application based on your ap.

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>
    <style>
        @media (prefers-color-scheme: dark) {// Dark modebody {
                background: # 333;
                color: white; }}@media (prefers-color-scheme: light) {// Use normal modebody {
                background: #ddd;
                color: black; }}</style>
</head>

<body>

    <h1>Electron demo</h1>
    <p>Current System Topics:<strong id="theme-source">System</strong></p>

    <button id="toggle-dark-mode">Toggle Dark Mode</button>
    <button id="reset-to-system">Reset to System Theme</button>
    <webview src='./other.html' webpreferences="nodeIntegration=true" id="webview">
    </webview>
    <script src="./renderer.js"></script>
</body>

</html>
Copy the code

renderer.js

const { ipcRenderer } = require("electron");

document
  .getElementById("toggle-dark-mode")
  .addEventListener("click".async() = > {const isDarkMode = await ipcRenderer.invoke("dark-mode:toggle");
    document.getElementById("theme-source").innerHTML = isDarkMode
      ? "Dark"
      : "Light";
  });

document
  .getElementById("reset-to-system")
  .addEventListener("click".async() = > {await ipcRenderer.invoke("dark-mode:system");
    document.getElementById("theme-source").innerHTML = "System";
  });
Copy the code

Main.js

ipcMain.handle("dark-mode:toggle".() = > {
  if (nativeTheme.shouldUseDarkColors) {// Check whether it is dark mode
    nativeTheme.themeSource = "light";
  } else {
    nativeTheme.themeSource = "dark";
  }
  return nativeTheme.shouldUseDarkColors;
});

ipcMain.handle("dark-mode:system".() = > {
  nativeTheme.themeSouce = "system";
});
Copy the code

Results show

The overall appearance has been changed so that we can follow the system. It is still a very handsome feature, but it may be a bit difficult to adapt

Embed web pages in electron

If we need to embed a third party’s web page, there are three ways to choose webView, iframe, and browserViews

Each approach provides slightly different functionality and can be useful in different situations. To help us choose the right external embedded web page for us, we began to explain the differences

  • webview

We do not recommend that we use this tag to embed third-party urls, as this tag has undergone significant architectural changes and may affect the stability of the application.

This tag is based on Google webViews, which doesn’t seem to explicitly support electron, so we can’t guarantee that some of the webView apis will work for electron in the future. In order to use webView we need to set it to true

main.js
function createWindow() {
  let win = new BrowserWindow({
    width: 1920.height: 1080.webPreferences: {
      nodeIntegration: true.webviewTag: true.// You need to set up the webView to enable this}});const contents = win.webContents;
  contents.openDevTools(); // Open the debugging tool
  win.loadURL("http://127.0.0.1:5500/2020-01-15/index.html"); } #index.. html <webview src='./other.html' webpreferences="nodeIntegration=true" id="webview">
  </webview>
nodeIntegration=trueThis means that embedded web pages will be able to use some of Node's featuresCopy the code

Since webViews are custom tags that only work inside ELECTRON, they are implemented as “out-of-process IFrame”, which means that all communication can only be done through IPC communication. Webview elements have a number of custom methods and events, similar to webContents, that give us more control over the content

It may be slightly slower to load than iframe, but it provides richer functionality and ipc communication mechanisms.

  • iframe

The behavior of the iframe here is similar to that of the browser; an iframe element allows us to load additional content as long as their content security policy allows. Iframe limits the number of features, sandbox properties are recommended, and only support the features you need

  • browserViews

This is not the function of the dom, it create and control is the main process to deal with, we can take advantage of the main process to create a new rendering process, its corresponding is a web page, which means that it created and the existing main form is complete, and is not controlled by the existing form, is a completely independent of the state, but still run by the master

BrowserViews provide the most control over their content because they implement webContents in a similar way to BrowserWindow, but because BrowserViews are not part of the DOM but overlay it, you must manually manage its location. Like opening a new window, doing something.

We have basically gone through the function module of electron, and the coverage points mainly cover the things we commonly use now, some not commonly used, just briefly covered. These are the methods provided by electron built-in, we still need to learn them again so that we can have this impression in our work and directly use them

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