跳转到主内容

Navigation History

概览​

The NavigationHistory class allows you to manage and interact with the browsing history of your Electron application. 这个强大的功能可让您为用户创建直观的导航体验。

用法​

Navigation history is stored per WebContents instance. 要访问导航历史类的具体实例,请使用 Webcontent 类contents.navigationHistory 实例属性。

const { BrowserWindow } = require('electron')

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

通过历史记录导航​

轻松实现前进和后退导航:

// 后退
if (navigationHistory.canGoBack()) {
navigationHistory.goBack()
}

// 前进
if (navigationHistory.canGoForward()) {
navigationHistory.goForward()
}

访问历史记录条目​

检索并显示用户浏览历史:

const entries = navigationHistory.getAllEntries()

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

Each navigation entry corresponds to a specific page. 索引系统依顺序排列:

  • 索引 0: 代表最早访问的页面。
  • 索引 N:代表最近访问的页面。

导航到特定条目​

允许用户跳转到他们浏览历史上的任何一点:

// 如果索引有效,则导航到历史记录中的第5个条目
navigationHistory.goToIndex(4)

// 导航至当前位置向前的第2个条目
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()
})