網頁內容 | webContents (webContents) - Electron 中文開發手冊
呈現和控制網頁。 Process: MainwebContents是一個EventEmitter。它負責渲染和控制網頁,並且是該BrowserWindow對象的屬性。訪問該webContents對象的示例:
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({width: 800, height: 1500})
win.loadURL('https://github.com')
let contents = win.webContents
console.log(contents)
方法
這些方法可以從webContents模塊訪問:
const {webContents} = require('electron')
console.log(webContents)
webContents.getAllWebContents()
返回WebContents[]- 所有WebContents實例的數組。這將包含所有窗口,網頁瀏覽,已打開的devtools和devtools擴展背景頁面的網頁內容。
webContents.getFocusedWebContents()
返回WebContents- 在此應用程序中關注的Web內容,否則返回null。
webContents.fromId(id)
id 整數返回WebContents- 具有給定ID的WebContents實例。
類:WebContents
渲染並控制BrowserWindow實例的內容。 過程:主
實例事件
Event: ‘did-finish-load’
導航完成onload時發出,即選項卡的旋轉器已停止旋轉,並且事件已發送。
Event: ‘did-fail-load’
返回:event EventerrorCode IntegererrorDescription StringvalidatedURL StringisMainFrame Boolean這個事件就像是did-finish-load在加載失敗或被取消時發出的,例如window.stop()被調用。錯誤代碼的完整列表及其含義可在此處找到。
Event: ‘did-frame-finish-load’
返回:event EventisMainFrame Boolean當一個框架完成導航時發射。
Event: ‘did-start-loading’
對應於選項卡的旋轉器開始旋轉時的時間點。
Event: ‘did-stop-loading’
對應於標簽的旋轉器停止旋轉的時間點。
Event: ‘did-get-response-details’
返回:event Eventstatus BooleannewURL StringoriginalURL StringhttpResponseCode IntegerrequestMethod Stringreferrer Stringheaders ObjectresourceType String當有關所請求資源的詳細信息可用時發出。status指示下載資源的套接字連接。
Event: ‘did-get-redirect-request’
返回:event EventoldURL StringnewURL StringisMainFrame BooleanhttpResponseCode IntegerrequestMethod Stringreferrer Stringheaders Object在請求資源時收到重定向時發出。
Event: ‘dom-ready’
返回:event Event加載給定幀中的文檔時發出。
Event: ‘page-favicon-updated’
返回:event Eventfavicons String[] - Array of URLs網頁收到圖標網址時發送。
Event: ‘new-window’
返回:event 事件url 串frameName 串disposition字符串-可以是default,foreground-tab,background-tab,new-window,save-to-disk和other。options對象 - 將用於創建新的選項BrowserWindow。additionalFeatures字符串[] - 給予的非標准功能(未由Chromium或Electron處理的功能)window.open()。當頁面請求打開一個新的窗口時發出url。它可以通過window.open或外部鏈接請求<a target='_blank'>。默認情況下,BrowserWindow將為該創建一個新的url。調用event.preventDefault()將阻止Electron自動創建新的BrowserWindow。如果您調用event.preventDefault()並手動創建新的,BrowserWindow則必須設置event.newGuest為引用新BrowserWindow實例,否則可能會導致意外行為。例如:
myBrowserWindow.webContents.on('new-window', (event, url) => {
event.preventDefault()
const win = new BrowserWindow({show: false})
win.once('ready-to-show', () => win.show())
win.loadURL(url)
event.newGuest = win
})
Event: ‘will-navigate’
返回:event Eventurl String當用戶或頁面想要開始導航時發射。當window.location對象發生更改或用戶單擊頁面中的鏈接時可能會發生這種情況。當導航以API webContents.loadURL和類似的API編程啟動時,此事件不會發出webContents.back。它也不會用於頁內導航,例如單擊錨鏈接或更新window.location.hash。 為此,請使用did-navigate-in-page事件。調用event.preventDefault()將阻止導航。
Event: ‘did-navigate’
返回:event Eventurl String導航完成時發射。此事件不是用於頁內導航的,例如單擊錨鏈接或更新window.location.hash。 為此,請使用did-navigate-in-page事件。
Event: ‘did-navigate-in-page’
返回:event Eventurl StringisMainFrame Boolean發生頁內導航時發出。當頁內導航發生時,頁面URL會發生變化,但不會導致頁面外的導航。發生這種情況的例子是當錨點鏈接被點擊或DOM hashchange事件被觸發時。
Event: ‘will-prevent-unload’
返回:event Eventbeforeunload事件處理程序試圖取消頁面卸載時發出。調用event.preventDefault()將忽略beforeunload事件處理程序並允許卸載頁面。
const {BrowserWindow, dialog} = require('electron')
const win = new BrowserWindow({width: 800, height: 600})
win.webContents.on('will-prevent-unload', (event) => {
const choice = dialog.showMessageBox(win, {
type: 'question',
buttons: ['Leave', 'Stay'],
title: 'Do you want to leave this site?',
message: 'Changes you made may not be saved.',
defaultId: 0,
cancelId: 1
})
const leave = (choice === 0)
if (leave) {
event.preventDefault()
}
})
Event: ‘crashed’
返回:event Eventkilled Boolean渲染器進程崩潰或被殺時發出。
Event: ‘plugin-crashed’
返回:event Eventname Stringversion String插件進程崩潰時發出。
Event: ‘destroyed’
webContents被銷毀時被發射。
Event: ‘before-input-event’
返回:event 事件input 對象 - 輸入屬性 type字符串 - keyUp或者keyDown key字符串 - 相當於KeyboardEvent.key code字符串 - 相當於KeyboardEvent.code isAutoRepeat布爾值 - 等同於KeyboardEvent.repeat shift布爾值 - 等同於KeyboardEvent.shiftKey control布爾值 - 相當於KeyboardEvent.controlKey alt布爾值 - 等同於KeyboardEvent.altKey meta布爾值 - 相當於KeyboardEvent.metaKey 分派前發射keydown和keyup活動頁面。調用event.preventDefault將阻止頁面keydown/ keyup事件和菜單快捷方式。要僅禁止菜單快捷方式,請使用setIgnoreMenuShortcuts:
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({width: 800, height: 600})
win.webContents.on('before-input-event', (event, input) => {
// For example, only enable application menu keyboard shortcuts when
// Ctrl/Cmd are down.
win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta)
})
Event: ‘devtools-opened’
DevTools打開時發出。
Event: ‘devtools-closed’
當DevTools關閉時發出。
Event: ‘devtools-focused’
在DevTools關注/打開時發出。
Event: ‘certificate-error’
返回:event 事件url 串error 字符串 - 錯誤代碼certificate 證書 callback 功能 isTrusted 布爾值 - 指示證書是否可以被視為可信當無法驗證發射certificate的url。用法與certificate-error事件相同app。
Event: ‘select-client-certificate’
返回:event Eventurl URLcertificateList Certificate[] callback Function certificate Certificate - Must be a certificate from the given list在請求客戶端證書時發送。用法與app的select-client-certificate事件相同。
Event: ‘login’
返回:event Eventrequest Object method Stringurl URLreferrer URLauthInfo Object isProxy Booleanscheme Stringhost Stringport Integerrealm Stringcallback Function username Stringpassword String在webContents想要進行基本身份驗證時發出。用法與app的登錄事件相同。
Event: ‘found-in-page’
返回:event 事件result 目的 requestId 整數activeMatchOrdinal 整數 - 活動比賽的位置。matches 整數 - 匹配數。selectionArea 對象 - 第一個匹配區域的坐標。finalUpdate 布爾當結果可用於webContents.findInPage請求時發出。
Event: ‘media-started-playing’
媒體開始播放時發射。
Event: ‘media-paused’
媒體暫停播放或播放完畢時播放。
Event: ‘did-change-theme-color’
頁面主題顏色改變時發出。這通常是由於遇到元標記:
<meta name='theme-color' content='#ff0000'>
Event: ‘update-target-url’
返回:event Eventurl String鼠標移過鏈接或鍵盤將焦點移動到鏈接時發出。
Event: ‘cursor-changed’
返回:event Eventtype Stringimage NativeImage (optional)scale Float (optional) - scaling factor for the custom cursorsize Size (optional) - the size of the image hotspot Point (optional) - coordinates of the custom cursor’s hotspot當游標類型改變時發射。所述type參數可以是default,crosshair,pointer,text,wait,help,e-resize,n-resize,ne-resize,nw-resize,s-resize,se-resize,sw-resize,w-resize,ns-resize,ew-resize,nesw-resize,nwse-resize,col-resize,row-resize,m-panning,e-panning,n-panning,ne-panning,nw-panning,s-panning,se-panning,sw-panning,w-panning,move,vertical-text,cell,context-menu,alias,progress,nodrop,copy,none,not-allowed,zoom-in,zoom-out,grab,grabbing,custom。如果type參數是custom,該image參數將舉行自定義光標圖像中NativeImage,和scale,size以及hotspot將舉行有關自定義光標的附加信息。
Event: ‘context-menu’
返回:event 事件params 目的 x 整數 - x坐標y 整數 - 並協調linkURL 字符串 - 封裝調用上下文菜單的節點的鏈接的URL。linkText字符串 - 與鏈接關聯的文本。如果鏈接的內容是圖像,可能是空字符串。pageURL 字符串 - 調用上下文菜單的頂級頁面的URL。frameURL 字符串 - 調用上下文菜單的子幀的URL。srcURL字符串 - 調用上下文菜單的元素的源URL。包含來源網址的元素是圖片,音頻和視頻。mediaTypeString - 上下文菜單被調用的節點的類型。可以none,image,audio,video,canvas,file或plugin。hasImageContents Boolean - 在具有非空內容的圖像上是否調用上下文菜單。isEditable 布爾型 - 上下文是否可編輯。selectionText 字符串 - 上下文菜單被調用的選擇文本。titleText 字符串 - 上下文被調用的選擇的標題或替代文本。misspelledWord 字符串 - 光標下的拼寫錯誤的單詞(如果有)。frameCharset 字符串 - 調用菜單的框架的字符編碼。inputFieldType字符串 - 如果上下文菜單在輸入字段上被調用,則該字段的類型。可能的值是none,plainText,password,other。menuSourceType字符串 - 調用上下文菜單的輸入源。可以none,mouse,keyboard,touch,touchMenu。mediaFlags Object - 調用上下文菜單的media元素的標志。 inError 布爾值 - 媒體元素是否已崩潰。isPaused 布爾值 - 媒體元素是否已暫停。isMuted 布爾值 - 媒體元素是否被靜音。hasAudio 布爾值 - 媒體元素是否具有音頻。isLooping 布爾值 - 媒體元素是否正在循環。isControlsVisible 布爾值 - 媒體元素的控件是否可見。canToggleControls 布爾值 - 媒體元素的控件是否可切換。canRotate 布爾值 - 媒體元素是否可以旋轉。
- `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action.
- `canUndo` Boolean - Whether the renderer believes it can undo.
- `canRedo` Boolean - Whether the renderer believes it can redo.
- `canCut` Boolean - Whether the renderer believes it can cut.
- `canCopy` Boolean - Whether the renderer believes it can copy
- `canPaste` Boolean - Whether the renderer believes it can paste.
- `canDelete` Boolean - Whether the renderer believes it can delete.
- `canSelectAll` Boolean - Whether the renderer believes it can select all.
當需要處理新的上下文菜單時發出。
Event: ‘select-bluetooth-device’
返回:event 事件devices BluetoothDevice類[] callback 功能 deviceId 串在調用時需要選擇藍牙設備時發射navigator.bluetooth.requestDevice。應該啟用使用navigator.bluetoothAPI webBluetooth。如果event.preventDefault未被調用,則將選擇第一個可用設備。callback應該被調用deviceId來選擇,傳遞空字符串callback將取消請求。
const {app, webContents} = require('electron')
app.commandLine.appendSwitch('enable-web-bluetooth')
app.on('ready', () => {
webContents.on('select-bluetooth-device', (event, deviceList, callback) => {
event.preventDefault()
let result = deviceList.find((device) => {
return device.deviceName === 'test'
})
if (!result) {
callback('')
} else {
callback(result.deviceId)
}
})
})
Event: ‘paint’
返回:event EventdirtyRect Rectangle image NativeImage - The image data of the whole frame.生成新幀時發射。只有臟區域被傳入緩沖區。
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({webPreferences: {offscreen: true}})
win.webContents.on('paint', (event, dirty, image) => {
// updateBitmap(dirty, image.getBitmap())
})
win.loadURL('https://github.com')
Event: ‘devtools-reload-page’
當devtools窗口指示webContents重新加載時發出
Event: ‘will-attach-webview’
返回:event 事件webPreferences對象 - 將由訪客頁面使用的Web首選項。可以修改此對象以調整訪客頁面的首選項。params對象 - 其他<webview>參數,如srcURL。可以修改此對象以調整訪客頁面的參數。當<webview>網站內容附加到網站內容時發送。通話event.preventDefault()將破壞訪客頁面。此事件可用於配置webPreferences的webContents的<webview>的加載在它之前,並提供了設置無法通過設置設置的功能<webview>屬性。注意:指定的preload腳本選項將顯示為preloadURL(不preload)在webPreferences此事件發出的對象中。
實例方法
contents.loadURL(url[, options])
url 串options 對象(可選) httpReferrer 字符串(可選) - HTTP引薦網址。userAgent 字符串(可選) - 發起請求的用戶代理。extraHeaders 字符串(可選) - 額外的標題由“\ n”分隔postData (UploadRawData [] | UploadFile [] | UploadFileSystem [] | UploadBlob []) - (可選)baseURLForDataURL字符串(可選) - 基礎URL(帶尾隨路徑分隔符)用於由數據URL加載的文件。只有當指定的url是數據url並需要加載其他文件時,才需要此選項。在窗口中加載網址。 該網址必須包含協議前綴,例如 http://或file://。 如果負載應該繞過http緩存,那么使用pragma頭來實現它。
const {webContents} = require('electron')
const options = {extraHeaders: 'pragma: no-cache\n'}
webContents.loadURL('https://github.com', options)
contents.downloadURL(url)
url 串在url無需導航的情況下啟動資源下載。該will-download事件session將被觸發。
contents.getURL()
返回String- 當前網頁的URL。
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('https://github.com')
let currentURL = win.webContents.getURL()
console.log(currentURL)
contents.getTitle()
返回String- 當前網頁的標題。
contents.isDestroyed()
返回Boolean- 網頁是否被銷毀。
contents.focus()
專注於網頁。
contents.isFocused()
返回Boolean- 網頁是否關注。
contents.isLoading()
返回Boolean- 網頁是否仍在加載資源。
contents.isLoadingMainFrame()
返回Boolean- 主框架(不僅僅是內部框架或框架中的框架)是否仍在加載。
contents.isWaitingForResponse()
返回Boolean- 網頁是否正在等待來自頁面主資源的第一個響應。
contents.stop()
停止任何掛起的導航。
contents.reload()
重新加載當前網頁。
contents.reloadIgnoringCache()
重新加載當前頁面並忽略緩存。
contents.canGoBack()
返回Boolean- 瀏覽器是否可以返回到之前的網頁。
contents.canGoForward()
返回Boolean- 瀏覽器是否可以轉到下一個網頁。
contents.canGoToOffset(offset)
offset Integer返回Boolean- 網頁是否可以進入offset。
contents.clearHistory()
清除導航歷史記錄。
contents.goBack()
使瀏覽器返回一個網頁。
contents.goForward()
使瀏覽器前進一個網頁。
contents.goToIndex(index)
index Integer將瀏覽器導航到指定的絕對網頁索引。
contents.goToOffset(offset)
offset Integer導航到“當前條目”的指定偏移量。
contents.isCrashed()
返回Boolean- 渲染器進程是否崩潰。
contents.setUserAgent(userAgent)
userAgent String覆蓋此網頁的用戶代理。
contents.getUserAgent()
返回String- 此網頁的用戶代理。
contents.insertCSS(css)
css String將CSS注入當前網頁。
contents.executeJavaScript(code[, userGesture, callback])
code 串userGesture布爾(可選) - 默認是false。callback 功能(可選) - 腳本執行后調用。 result 任何返回Promise- 一種以執行代碼的結果解決的承諾,或者如果代碼的結果是被拒絕的承諾,則被拒絕。code在頁面中進行評估。在瀏覽器窗口requestFullScreen中,只能通過用戶的手勢調用某些HTML API 。設置userGesture為true將刪除此限制。如果執行的代碼的結果是promise,則回調結果將是promise的解析值。我們建議您使用返回的Promise來處理導致Promise的代碼。
contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true)
.then((result) => {
console.log(result) // Will be the JSON object from the fetch call
})
contents.setIgnoreMenuShortcuts(ignore) Experimental
ignore Boolean此Web內容的焦點時忽略應用程序菜單快捷方式。
contents.setAudioMuted(muted)
muted Boolean將當前網頁上的音頻靜音。
contents.isAudioMuted()
返回Boolean- 此頁面是否已被靜音。
contents.setZoomFactor(factor)
factor Number - Zoom factor.將縮放系數更改為指定的系數。縮放系數是縮放百分比除以100,所以300%= 3.0。
contents.getZoomFactor(callback)
callback Function zoomFactor Number發送請求以獲取當前縮放因子,callback將會使用該參數調用callback(zoomFactor)。
contents.setZoomLevel(level)
level Number - Zoom level將縮放級別更改為指定級別。原始大小為0,每個增量高於或低於分別代表縮小20%或更小,分別默認為原始大小的300%和50%。
contents.getZoomLevel(callback)
callback Function zoomLevel Number發送請求以獲取當前縮放級別,callback將會使用該級別調用callback(zoomLevel)。
contents.setZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevel NumbermaximumLevel Number棄用:setVisualZoomLevelLimits改為調用可視縮放級別限制。Electron 2.0將刪除此方法。
contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevel NumbermaximumLevel Number設置最大和最小捏縮放級別。
contents.setLayoutZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevel NumbermaximumLevel Number設置最大和最小布局(即非可視)縮放級別。
contents.undo()
執行undo網頁中的編輯命令。
contents.redo()
執行redo網頁中的編輯命令。
contents.cut()
執行cut網頁中的編輯命令。
contents.copy()
執行copy網頁中的編輯命令。
contents.copyImageAt(x, y)
x Integery Integer將給定位置的圖像復制到剪貼板。
contents.paste()
執行paste網頁中的編輯命令。
contents.pasteAndMatchStyle()
執行pasteAndMatchStyle網頁中的編輯命令。
contents.delete()
執行delete網頁中的編輯命令。
contents.selectAll()
執行selectAll網頁中的編輯命令。
contents.unselect()
執行unselect網頁中的編輯命令。
contents.replace(text)
text String執行replace網頁中的編輯命令。
contents.replaceMisspelling(text)
text String執行replaceMisspelling網頁中的編輯命令。
contents.insertText(text)
text String插入text到被聚焦的元素。
contents.findInPage(text[, options])
text 字符串 - 要搜索的內容不能為空。options 對象(可選) forward布爾值 - (可選)是向前還是向后搜索,默認值為true。findNext布爾值 - (可選)操作是第一次請求還是后續操作,默認為false。matchCase布爾值 - (可選)搜索是否區分大小寫,默認為false。wordStart布爾 - (可選)是否僅查看單詞的開頭。默認為false。medialCapitalAsWordStart布爾值 - (可選)結合使用時wordStart,如果匹配以大寫字母后跟小寫字母或非字母開頭,則接受單詞中間的匹配。接受其他幾個詞內匹配,默認為false。開始請求查找text網頁中的所有匹配項,並返回一個Integer表示請求使用的請求ID。請求的結果可以通過訂閱found-in-page事件來獲得。
contents.stopFindInPage(action)
action字符串 - 指定結束webContents.findInPage請求時要執行的操作。clearSelection - 清除選擇。keepSelection - 將選擇轉換為正常選擇。activateSelection - 重點並單擊選擇節點。使用提供的操作停止webContents的任何findInPage請求。
const {webContents} = require('electron')
webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) webContents.stopFindInPage('clearSelection')
})
const requestId = webContents.findInPage('api')
console.log(requestId)
contents.capturePage([rect, ]callback)
rect 矩形(可選) - 要捕獲的頁面區域callback 功能 image NativeImage 捕獲內部頁面的快照rect。完成callback后將被稱為callback(image)。image是一個存儲快照數據的NativeImage實例。省略rect將捕捉整個可見頁面。
contents.hasServiceWorker(callback)
callback 功能 hasWorker 布爾檢查是否有ServiceWorker注冊並返回一個布爾值作為響應callback。
contents.unregisterServiceWorker(callback)
callback 功能 success 布爾取消注冊任何ServiceWorker(如果存在),並返回一個布爾值作為對callbackJS承諾何時執行的響應,或當JS承諾被拒絕時返回false。
contents.getPrinters()
獲取系統打印機列表。返回 PrinterInfo[]
contents.print([options])
options 對象(可選) silent布爾(可選) - 不要求用戶進行打印設置。默認是false。printBackground布爾(可選) - 還打印網頁的背景顏色和圖像。默認是false。deviceName字符串(可選) - 設置要使用的打印機設備名稱。默認是''。打印窗口的網頁。如果silent設置為true,Electron將選擇系統的默認打印機(如果deviceName為空)以及打印的默認設置。調用window.print()網頁等同於調用webContents.print({silent: false, printBackground: false, deviceName: ''})。使用page-break-before: always;CSS樣式強制打印到新頁面。
contents.printToPDF(options, callback)
options 對象marginsType整數 - (可選)指定要使用的邊距類型。默認邊距使用0,無邊距使用1,最小邊距使用2。pageSize字符串 - (可選)指定生成的PDF的頁面大小。可以A3,A4,A5,Legal,Letter,Tabloid或包含對象height,並width在微米。printBackground 布爾值 - (可選)是否打印CSS背景。printSelectionOnly 布爾值 - (可選)是否僅打印選擇。landscape布爾 - (可選)true橫向,false縱向。callback 功能 error 錯誤data 緩沖使用Chromium的預覽打印自定義設置將窗口的網頁打印為PDF。回調將在回調(錯誤,數據)完成時調用。 數據是包含生成的PDF數據的緩沖區。如果在網頁中使用@page CSS at-rule,則該景觀將被忽略。默認情況下,空白options將被視為:
{
marginsType: 0,
printBackground: false,
printSelectionOnly: false,
landscape: false
}
使用page-break-before: always;CSS樣式強制打印到新頁面。一個webContents.printToPDF例子:
const {BrowserWindow} = require('electron')
const fs = require('fs')
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('https://github.com')
win.webContents.on('did-finish-load', () => {
// Use default printing options
win.webContents.printToPDF({}, (error, data) => {
if (error) throw error
fs.writeFile('/tmp/print.pdf', data, (error) => {
if (error) throw error
console.log('Write PDF successfully.')
})
})
})
contents.addWorkSpace(path)
path String將指定的路徑添加到DevTools工作區。必須在DevTools創建后使用:
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname)
})
contents.removeWorkSpace(path)
path String從DevTools工作區中刪除指定的路徑。
contents.openDevTools([options])
options 對象(可選) mode字符串-打開與指定的停靠狀態devtools,可以是right,bottom,undocked,detach。默認為上次使用的碼頭狀態。在undocked模式下可以停靠。在detach模式中不是。打開devtools。
contents.closeDevTools()
關閉devtools。
contents.isDevToolsOpened()
返回Boolean- devtools是否被打開。
contents.isDevToolsFocused()
返回Boolean- devtools視圖是否集中。
contents.toggleDevTools()
切換開發人員工具。
contents.inspectElement(x, y)
x Integery Integer在位置(x,y)開始檢查元素。
contents.inspectServiceWorker()
打開服務工作者上下文的開發人員工具。
contents.send(channel[, arg1][, arg2][, ...])
channel String...args any[]通過向渲染器進程發送異步消息channel,您還可以發送任意參數。參數將在JSON內部序列化,因此不會包含函數或原型鏈。渲染過程可以通過監聽處理消息channel與ipcRenderer模塊。從主進程向渲染進程發送消息的示例:
// In the main process.
const {app, BrowserWindow} = require('electron')
let win = null
app.on('ready', () => {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => {
win.webContents.send('ping', 'whoooooooh!')
})
})
<!-- index.html -->
<html>
<body>
<script>
require('electron').ipcRenderer.on('ping', (event, message) => {
console.log(message) // Prints 'whoooooooh!'
})
</script>
</body>
</html>
contents.enableDeviceEmulation(parameters)
parameters對象 screenPosition字符串-指定的屏幕類型效仿(默認值:desktop)desktop - 桌面屏幕類型mobile - 屏幕類型
- `screenSize` [Size](../structures/size/index) - Set the emulated screen size (screenPosition == mobile)
- `viewPosition` [Point](../structures/point/index) - Position the view on the screen (screenPosition == mobile) (default: `{x: 0, y: 0}`)
- `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to original device scale factor) (default: `0`)
- `viewSize` [Size](../structures/size/index) - Set the emulated view size (empty means no override)
- `fitToView` Boolean - Whether emulated view should be scaled down if necessary to fit into available space (default: `false`)
- `offset` [Point](../structures/point/index) - Offset of the emulated view inside available space (not in fit to view mode) (default: `{x: 0, y: 0}`)
- `scale` Float - Scale of emulated view inside available space (not in fit to view mode) (default: `1`)
使用給定參數啟用設備仿真。
contents.disableDeviceEmulation()
禁用啟用的設備仿真webContents.enableDeviceEmulation。
contents.sendInputEvent(event)
event 目的 type串(所需) -的事件的類型,可以是mouseDown,mouseUp,mouseEnter,mouseLeave,contextMenu,mouseWheel,mouseMove,keyDown,keyUp,char。modifiers串[] -事件的改性劑組成的數組,可以包括shift,control,alt,meta,isKeypad,isAutoRepeat,leftButtonDown,middleButtonDown,rightButtonDown,capsLock,numLock,left,right。將輸入發送event到頁面。注:本BrowserWindow包含內容需要集中的sendInputEvent()工作。對於鍵盤事件,該event對象還具有以下屬性:keyCode字符串(必需) - 將作為鍵盤事件發送的字符。只應使用加速器中的有效密鑰代碼。對於鼠標事件,該event對象還具有以下屬性:x整數(必需)y整數(必需)button字符串-按下按鈕,可以left,middle,right globalX 整數globalY 整數movementX 整數movementY 整數clickCount 整數對於該mouseWheel事件,該event對象還具有以下屬性:deltaX 整數deltaY 整數wheelTicksX 整數wheelTicksY 整數accelerationRatioX 整數accelerationRatioY 整數hasPreciseScrollingDeltas 布爾canScroll 布爾
contents.beginFrameSubscription([onlyDirty ,]callback)
onlyDirty 布爾(可選) - 默認為 false callback 功能 frameBuffer 緩沖dirtyRect 長方形 開始訂閱演示文稿事件和捕獲的幀,當有演示事件時callback將被callback(frameBuffer, dirtyRect)調用。這frameBuffer是一個Buffer包含原始像素數據。在大多數機器上,像素數據以32位BGRA格式有效存儲,但實際表示取決於處理器的字節順序(大多數現代處理器是小端,在具有高端處理器的機器上,數據采用32位ARGB格式) 。dirtyRect是一個具有x,y,width,height屬性的對象,用於描述頁面的哪一部分已重新繪制。 如果僅將dirty設置為true,則frameBuffer將只包含重繪區域。 只有臟的默認值為false。
contents.endFrameSubscription()
結束訂閱幀展示事件。
contents.startDrag(item)
item 對象 file字符串或files數組 - 被拖動的文件的路徑。icon NativeImage - macOS上的圖像必須是非空的。設置item為當前拖放操作的拖動項目,file是要拖動的文件的絕對路徑,拖動icon時顯示在光標下的圖像。
contents.savePage(fullPath, saveType, callback)
fullPath 字符串 - 完整的文件路徑。saveType 字符串 - 指定保存類型。 HTMLOnly - 只保存頁面的HTML。HTMLComplete - 保存完整的HTML頁面。MHTML - 將完整的html頁面保存為MHTML。callback功能 - (error) => {}。error 錯誤返回Boolean- 如果保存頁面的過程已成功啟動,則為true。
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.on('did-finish-load', () => {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete', (error) => {
if (!error) console.log('Save page successfully')
})
})
contents.showDefinitionForSelection() macOS
顯示用於搜索頁面上所選單詞的彈出式字典。
contents.setSize(options)
設置頁面的大小。這僅適用於<webview>訪客內容。options 目的 normal對象(可選) - 頁面的正常大小。這可以與該disableguestresize屬性結合使用以手動調整webview客人內容的大小。width 整數height 整數
contents.isOffscreen()
返回Boolean- 指示是否啟用離線渲染。
contents.startPainting()
如果離線渲染啟用而不是繪畫,請開始繪畫。
contents.stopPainting()
如果屏幕外渲染已啟用並且繪畫,請停止繪畫。
contents.isPainting()
返回Boolean- 如果啟用了屏幕外渲染,則返回它是否正在繪制。
contents.setFrameRate(fps)
fps Integer如果啟用了屏幕外渲染,則將幀速率設置為指定的數字。只有1到60之間的值才被接受。
contents.getFrameRate()
返回Integer- 如果啟用了屏幕外渲染,則返回當前幀速率。
contents.invalidate()
計划對該網頁內容所在的窗口進行完整重繪。如果啟用了屏幕外渲染,則會使該幀無效並通過該'paint'事件生成新的。
contents.getWebRTCIPHandlingPolicy()
返回String- 返回WebRTC IP處理策略。
contents.setWebRTCIPHandlingPolicy(policy)
policy 字符串 - 指定WebRTC IP處理策略。 default - 公開用戶的公共和本地IP。這是默認行為。使用此策略時,WebRTC有權枚舉所有接口並綁定它們以發現公共接口。default_public_interface_only - 公開用戶的公共IP,但不公開用戶的本地IP。使用此策略時,WebRTC應僅使用http使用的默認路由。這不會公開任何本地地址。default_public_and_private_interfaces - 公開用戶的公共和本地IP。使用此策略時,WebRTC應僅使用http使用的默認路由。這也暴露了相關的默認私人地址。默認路由是OS在多宿主端點上選擇的路由。disable_non_proxied_udp - 不公開或本地IP。使用此策略時,除非代理服務器支持UDP,否則WebRTC應僅使用TCP聯系對等或服務器。通過設置WebRTC IP處理策略,您可以控制哪些IP通過WebRTC公開。有關更多詳細信息,請參閱BrowserLeaks。
contents.getOSProcessId()
返回Integer- pid關聯的渲染器進程的。
實例屬性
contents.id
Integer表示此WebContents的唯一ID。
contents.session
一個Session由此webContents使用的。
contents.hostWebContents
一個WebContents可能擁有這個的實例WebContents。
contents.devToolsWebContents
一個WebContentsDevTools為此WebContents。注意:用戶不應該存儲這個對象,因為null當DevTools關閉時它可能會變成。
contents.debugger
此webContents的調試器實例。
