Electron 與遠(yuǎn)端頁面交互使用本地資源

Electron 頁面加載方式有兩種:

  • 加載本地文件
  • 通過 http 網(wǎng)絡(luò)請求頁面

加載本地資源的文件可以很方便的使用本地環(huán)境。此處不再贅述。但是在 http 請求的資源中,我們?nèi)绾握{(diào)用到 electron/NodeJS 的 API 呢?答案是使用 electron 提供的 preload 方法來給頁面附加 nodejs/electron 運(yùn)行環(huán)境。

關(guān)于 preload

preload 是 electron 的 BrowserWindow 提供的一種預(yù)加載的腳本。該腳本在頁面運(yùn)行其他腳本之前運(yùn)行。在該腳本中,無論頁面是否集成了 Nodejs,此腳本中的內(nèi)容都可以訪問所有的 NodeJS API。

preload 的詳細(xì)信息參考BrowserWindow

代碼參考

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script>
    console.log("111111")
    window.fromWebToElectron('test 11111', function(a){
      console.log("get data from aaaaa ", a)
    })
    window.ifElectronWantClose = function(a){
      console.log("electron told window need to close, ", a)
    }
    window.saveDataToFile('aaa', 'aaaa1', function(a){
      console.log('electron write data aaaa1 to file aaa');
    })
    window.saveDataToFileSuccessListener = function(a){
      console.log("electron write data aaaa1 to file, ", a)
    }
  </script>
</head>
<body>
First Pages
</body>
</html>

Main.js

const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')

let mainWindow

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadURL(html 地址)

  mainWindow.on('closed', function () {
    mainWindow = null
  })
}

ipcMain.on('close', (e, a) => {
  mainWindow.webContents.send('ifElectronWantClose', [a]);
});

ipcMain.on('write_file_success', (e, a) => {
  mainWindow.webContents.send('saveDataToFileSuccessListener', [a]);
});

app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  if (mainWindow === null) createWindow()
})

Preload.js

// electron接收傳參或主動(dòng)talk

// preload.js

let {ipcRenderer} = require('electron');
let fs = require('fs');
let path = require('path');

window.saveDataToFile = function (name, fileString, callback) {
    let fPath = path.join('C:\\Users\\melon\\Desktop\\新建文件夾', name);
    fs.writeFileSync(fPath, fileString);
    callback(`write file to ${'fPath'} success`);
    ipcRenderer.send('write_file_success', 'args aaa'); // 比如收到請求關(guān)閉窗口
};

ipcRenderer.on('saveDataToFileSuccessListener', (e, args) => {
    window.saveDataToFileSuccessListener(args[0]);
});

window.fromWebToElectron = function (a, callback) {
    console.log('electron收到遠(yuǎn)端的傳參', a);
    callback('config result'); // 回調(diào)給遠(yuǎn)端的請求數(shù)據(jù),如 config
    ipcRenderer.send('close', 'args bbb'); // 比如收到請求關(guān)閉窗口
};

ipcRenderer.on('ifElectronWantClose', (e, args) => {
    window.ifElectronWantClose(args[0]);
});

至此,我們只要在 preload 中提供了適當(dāng)?shù)姆椒?,就可以通過 https 加載遠(yuǎn)端的網(wǎng)頁操作本地資源了。

運(yùn)行效果如圖:

效果.jpg

關(guān)于 sandbox

當(dāng) webPreferencessandbox 設(shè)置為 true 的時(shí)候,preload 中的腳本能夠調(diào)用的 API 被限制了。僅能夠訪問到 electron 的一部分 API。但是這時(shí)候可以通過 IPC 通信的機(jī)制,使用主進(jìn)程來訪問被限制的 API。對安全考慮較多的,可以考慮使用這個(gè)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容