跳到主要內容

導覽歷史

總覽

NavigationHistory 類別允許您管理和與您的 Electron 應用程式的瀏覽歷史互動。這個強大的功能使您能夠為您的使用者創造直觀的導覽體驗。

存取 NavigationHistory

導覽歷史是針對每個 WebContents 實例儲存的。要存取 NavigationHistory 類別的特定實例,請使用 WebContents 類別的 contents.navigationHistory 實例屬性

const { BrowserWindow } = require('electron')

const mainWindow = new BrowserWindow()
const { navigationHistory } = mainWindow.webContents

輕鬆實現返回和前進導覽

// Go back
if (navigationHistory.canGoBack()) {
navigationHistory.goBack()
}

// Go forward
if (navigationHistory.canGoForward()) {
navigationHistory.goForward()
}

存取歷史記錄條目

檢索並顯示使用者的瀏覽歷史

const entries = navigationHistory.getAllEntries()

entries.forEach((entry) => {
console.log(`${entry.title}: ${entry.url}`)
})

每個導覽條目都對應到特定的頁面。索引系統遵循順序

  • 索引 0:表示最早訪問的頁面。
  • 索引 N:表示最近訪問的頁面。

允許使用者跳到他們瀏覽歷史中的任何點

// Navigate to the 5th entry in the history, if the index is valid
navigationHistory.goToIndex(4)

// Navigate to the 2nd entry forward from the current position
if (navigationHistory.canGoToOffset(2)) {
navigationHistory.goToOffset(2)
}

這是一個完整的範例,您可以用 Electron Fiddle 開啟

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

function createWindow () {
const mainWindow = new BrowserWindow({
width: 1000,
height: 800,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true
}
})

mainWindow.loadFile('index.html')

const view = new BrowserView()
mainWindow.setBrowserView(view)
view.setBounds({ x: 0, y: 100, width: 1000, height: 800 })
view.setAutoResize({ width: true, height: true })

const navigationHistory = view.webContents.navigationHistory
ipcMain.handle('nav:back', () =>
navigationHistory.goBack()
)

ipcMain.handle('nav:forward', () => {
navigationHistory.goForward()
})

ipcMain.handle('nav:canGoBack', () => navigationHistory.canGoBack())
ipcMain.handle('nav:canGoForward', () => navigationHistory.canGoForward())
ipcMain.handle('nav:loadURL', (_, url) =>
view.webContents.loadURL(url)
)
ipcMain.handle('nav:getCurrentURL', () => view.webContents.getURL())
ipcMain.handle('nav:getHistory', () => {
return navigationHistory.getAllEntries()
})

view.webContents.on('did-navigate', () => {
mainWindow.webContents.send('nav:updated')
})

view.webContents.on('did-navigate-in-page', () => {
mainWindow.webContents.send('nav:updated')
})
}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})