webContents
ウェブページを描画、制御します。
Process: Main
webContents は EventEmitter を継承しています。 It is responsible for rendering and controlling a web page and is a property of the BrowserWindow object. 以下は、webContents オブジェクトにアクセスする例です。
const{BrowserWindow}=require('electron')
const win =newBrowserWindow({width:800,height:1500})
win.loadURL('https://github.com')
const contents = win.webContents
console.log(contents)
ナビゲーションイベント
いくつかのイベントは webContents 内で発生するナビゲーションの監視に使用できます。
ドキュメントのナビゲーション
When a webContents navigates to another page (as opposed to an in-page navigation), the following events will be fired.
did-start-navigationwill-frame-navigatewill-navigate(only fired when main frame navigates)will-redirect(only fired when a redirect happens during navigation)did-redirect-navigation(only fired when a redirect happens during navigation)did-frame-navigatedid-navigate(only fired when main frame navigates)
event.preventDefault() がキャンセル可能なイベントで呼び出された場合、それ以降のイベントは発生しません。
ページ内ナビゲーション
ページ内ナビゲーションとは、ページのリロードを引き起こすのではなく、現在のページ内のとある場所へナビゲーションするものです。 これらのイベントはキャンセルできません。 ページ内ナビゲーションでは、次のイベントがこの順序で発生します。
フレームのナビゲーション
The will-navigate and did-navigate events only fire when the mainFrame navigates. If you want to also observe navigations in <iframe>s, use will-frame-navigate and did-frame-navigate events.
メソッド
これらのメソッドは、webContents モジュールからアクセスできます。
const{ webContents }=require('electron')
console.log(webContents)
webContents.getAllWebContents()
戻り値 WebContents[] - すべての WebContents インスタンスの配列。 これには、すべてのウインドウ、開かれた開発者向けツール、開発者向けツールのバックグラウンド拡張のページが含まれます。
webContents.getFocusedWebContents()
戻り値 WebContents | null - このアプリケーション内でフォーカス中のウェブコンテンツ。無ければ null。
webContents.fromId(id)
idInteger
戻り値 WebContents | undefined - 指定 ID の WebContents インスタンス。指定 ID に関連付けられた WebContents が存在しない場合は undefined です。
webContents.fromFrame(frame)
frameWebFrameMain
戻り値 WebContents | undefined - 指定 WebFrameMain の WebContents インスタンス。指定の WebFrameMain に関連付けられた WebContents が存在しない場合は undefined です。
webContents.fromDevToolsTargetId(targetId)
targetIdstring - WebContents インスタンスに関連付けられた Chrome デベロッパー ツールプロトコルの TargetID。
戻り値 WebContents | undefined - 指定 TargetID の WebContents インスタンス。指定 TargetID に関連付けられた WebContents が存在しない場合は undefined です。
Chrome デベロッパー ツールプロトコル と通信する際に、割り当てられた TargetID で WebContents インスタンスを検索すると便利な場合があります。
asyncfunctionlookupTargetId(browserWindow){
const wc = browserWindow.webContents
await wc.debugger.attach('1.3')
const{ targetInfo }=await wc.debugger.sendCommand('Target.getTargetInfo')
const{ targetId }= targetInfo
const targetWebContents =await wc.fromDevToolsTargetId(targetId)
}
クラス: WebContents
BrowserWindow インスタンスのコンテンツを、描画し、制御します。
Process: Main
This class is not exported from the 'electron' module. Electron API では、他のメソッドの戻り値としてのみ利用できます。
インスタンスイベント
イベント: 'did-finish-load'
ナビゲーションが終了した時、すなわち、タブのくるくるが止まったときや、onload イベントが送られた後に、発行されます。
イベント: 'did-fail-load'
戻り値:
eventEventerrorCodeIntegererrorDescriptionstringvalidatedURLstringisMainFramebooleanframeProcessIdIntegerframeRoutingIdInteger
このイベントは did-finish-load に似ていますが、ロードが失敗したときも発行されます。 エラーコードとその意味のすべてのリストは こちら です。
イベント: 'did-fail-provisional-load'
戻り値:
eventEventerrorCodeIntegererrorDescriptionstringvalidatedURLstringisMainFramebooleanframeProcessIdIntegerframeRoutingIdInteger
このイベントは did-fail-load に似ていますが、ロードがキャンセルされたときに発行されます (例えば window.stop() が呼び出されたときなど)。
イベント: 'did-frame-finish-load'
戻り値:
eventEventisMainFramebooleanframeProcessIdIntegerframeRoutingIdInteger
フレームのナビゲーションが終了したときに発行されます。
イベント: 'did-start-loading'
タブのくるくるが始まったタイミングに対応しています。
イベント: 'did-stop-loading'
タブのくるくるが止まったタイミングに対応しています。
イベント: 'dom-ready'
最上位フレームの document が読み込まれたときに発生します。
イベント: 'page-title-updated'
戻り値:
eventEventtitlestringexplicitSetboolean
ナビゲーション中にページタイトルが設定されると発生します。 explicitSet は、タイトルがファイル URL から合成されている場合に false になります。
イベント: 'page-favicon-updated'
戻り値:
eventEventfaviconsstring[] - URLの配列。
ページがファビコンの URL を受け取ると発行されます。
イベント: 'content-bounds-updated'
戻り値:
eventEventboundsRectangle - requested new content bounds
ページが window.moveTo、 window.resizeTo 、または関連する API を呼び出すときに発生します。
デフォルトでは、これによりウインドウを動かします。 その動作を阻害するには、event.preventDefault() を呼び出してください。
イベント: 'did-create-window'
戻り値:
windowBrowserWindowdetailsObjecturlstring - 作成したウインドウの URL。frameNamestring -window.open()の呼び出しで作成したウインドウに指定した名前。referrerReferrer - The referrer that will be passed to the new window. リファラのポリシーに応じたRefererヘッダーが送信されるとは限りません。postBodyPostBody (任意) - 新しいウィンドウに送信される POST データと、設定される適切なヘッダです。 送信する POST データが無い場合、値はnullになります。 これはtarget=_blankを設定したフォームによってウィンドウが作成されている場合にのみセットされます。dispositionstring -default、foreground-tab、background-tab、new-window、otherにできます。
レンダラーで window.open を使用したウィンドウの作成に成功した 後 に発生します。 Not emitted if the creation of the window is canceled from webContents.setWindowOpenHandler.
詳細や webContents.setWindowOpenHandler と併せた使用方法については window.open() をご参照ください。
イベント: 'will-navigate'
戻り値:
detailsEvent<>urlstring - フレームがナビゲーションしようとしている URL。isSameDocumentboolean - このイベントは、window.history API による同一ドキュメントのナビゲーションと参照フラグメントのナビゲーションでは発生しません。 このイベントでのこのプロパティは、常にfalseがセットされています。isMainFrameboolean - ナビゲーションがメインフレームで行われている場合は true です。frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith a frame's name), or null if the navigation was not initiated by a frame. イベントの発生前に開始したフレームが削除された場合も null になることがあります。
urlstring 非推奨isInPlaceboolean 非推奨isMainFrameboolean 非推奨frameProcessIdInteger 非推奨frameRoutingIdInteger 非推奨
メインフレーム上でユーザーまたはページがナビゲーションを開始しようとしたときに発生します。 window.location オブジェクトが変更されるか、ユーザがページ内のリンクをクリックしたときに発生することがあります。
このイベントは、 webContents.loadURL や webContents.back のような API によって、プログラム上から開始されるナビゲーションのときには発行されません。
これは、アンカーリンクのクリックや window.location.hash の更新のような、ページ内ナビゲーションでも発行されません。 これを意図する場合は did-navigate-in-page を使用して下さい。
event.preventDefault() を呼ぶとナビゲーションが阻害されます。
イベント: 'will-frame-navigate'
戻り値:
detailsEvent<>urlstring - フレームがナビゲーションしようとしている URL。isSameDocumentboolean - このイベントは、window.history API による同一ドキュメントのナビゲーションと参照フラグメントのナビゲーションでは発生しません。 このイベントでのこのプロパティは、常にfalseがセットされています。isMainFrameboolean - ナビゲーションがメインフレームで行われている場合は true です。frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith a frame's name), or null if the navigation was not initiated by a frame. イベントの発生前に開始したフレームが削除された場合も null になることがあります。
ユーザーまたはページが任意のフレームでナビゲーションを開始しようとしたときに発生します。 window.location オブジェクトが変更されるか、ユーザがページ内のリンクをクリックしたときに発生することがあります。
will-navigate とは異なり、will-frame-navigate はメインフレームまたはそのサブフレームのいずれかがナビゲートしようとしたときに発生します。 ナビゲーションイベントがメインフレームから来た場合、isMainFrame は true になります。
このイベントは、 webContents.loadURL や webContents.back のような API によって、プログラム上から開始されるナビゲーションのときには発行されません。
これは、アンカーリンクのクリックや window.location.hash の更新のような、ページ内ナビゲーションでも発行されません。 これを意図する場合は did-navigate-in-page を使用して下さい。
event.preventDefault() を呼ぶとナビゲーションが阻害されます。
イベント: 'did-start-navigation'
戻り値:
detailsEvent<>urlstring - フレームがナビゲーションしようとしている URL。isSameDocumentboolean - ドキュメントが変わらずにナビゲーションが行われたかどうか。 同一ドキュメントでのナビゲーションの例としては、参照フラグメントナビゲーション、pushState/replaceState、同一ページの履歴のナビゲーションなどがあります。isMainFrameboolean - ナビゲーションがメインフレームで行われている場合は true です。frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith a frame's name), or null if the navigation was not initiated by a frame. イベントの発生前に開始したフレームが削除された場合も null になることがあります。
urlstring 非推奨isInPlaceboolean 非推奨isMainFrameboolean 非推奨frameProcessIdInteger 非推奨frameRoutingIdInteger 非推奨
フレーム (メインを含む) がナビゲーションを始めているときに発生します。
イベント: 'will-redirect'
戻り値:
detailsEvent<>urlstring - フレームがナビゲーションしようとしている URL。isSameDocumentboolean - ドキュメントが変わらずにナビゲーションが行われたかどうか。 同一ドキュメントでのナビゲーションの例としては、参照フラグメントナビゲーション、pushState/replaceState、同一ページの履歴のナビゲーションなどがあります。isMainFrameboolean - ナビゲーションがメインフレームで行われている場合は true です。frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith a frame's name), or null if the navigation was not initiated by a frame. イベントの発生前に開始したフレームが削除された場合も null になることがあります。
urlstring 非推奨isInPlaceboolean 非推奨isMainFrameboolean 非推奨frameProcessIdInteger 非推奨frameRoutingIdInteger 非推奨
ナビゲーション後にサーバーサイドリダイレクトが起きたときに発生します。 302 リダイレクトなどがその例です。
このイベントは常に、同一ナビゲーションで did-start-navigation の後かつ did-redirect-navigation イベントの前に発行されます。
event.preventDefault() を呼ぶとナビゲーション (リダイレクトではない) が阻害されます。
イベント: 'did-redirect-navigation'
戻り値:
detailsEvent<>urlstring - フレームがナビゲーションしようとしている URL。isSameDocumentboolean - ドキュメントが変わらずにナビゲーションが行われたかどうか。 同一ドキュメントでのナビゲーションの例としては、参照フラグメントナビゲーション、pushState/replaceState、同一ページの履歴のナビゲーションなどがあります。isMainFrameboolean - ナビゲーションがメインフレームで行われている場合は true です。frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith a frame's name), or null if the navigation was not initiated by a frame. イベントの発生前に開始したフレームが削除された場合も null になることがあります。
urlstring 非推奨isInPlaceboolean 非推奨isMainFrameboolean 非推奨frameProcessIdInteger 非推奨frameRoutingIdInteger 非推奨
ナビゲーション後にサーバーサイドリダイレクトが発生すると発行されます。 302 リダイレクトなどがその例です。
このイベントを阻害することはできません。リダイレクトを防ぎたい場合は、上記の will-redirect イベントを確認してください。
イベント: 'did-navigate'
戻り値:
eventEventurlstringhttpResponseCodeInteger - HTTP ナビゲーションが無い場合は-1httpStatusTextstring - HTTP ナビゲーションが無い場合は空
メインフレームのナビゲーションが完了したときに発生します。
このイベントは、アンカーリンクのクリックや window.location.hash の更新のような、ページ内ナビゲーションでは発行されません。 これを意図する場合は did-navigate-in-page を使用して下さい。
イベント: 'did-frame-navigate'
戻り値:
eventEventurlstringhttpResponseCodeInteger - HTTP ナビゲーションが無い場合は-1httpStatusTextstring - 非 HTTP ナビゲーションでは空です。isMainFramebooleanframeProcessIdIntegerframeRoutingIdInteger
フレームのナビゲーションが完了したときに発生します。
このイベントは、アンカーリンクのクリックや window.location.hash の更新のような、ページ内ナビゲーションでは発行されません。 これを意図する場合は did-navigate-in-page を使用して下さい。
イベント: 'did-navigate-in-page'
戻り値:
eventEventurlstringisMainFramebooleanframeProcessIdIntegerframeRoutingIdInteger
フレームのページ内ナビゲーションが発生したときに発生します。
ページ内ナビゲーションが行われるとき、ページのURLは変更されますがページ外でのナビゲーションは発生しません。 これが発生する例は、アンカーリンクがクリックされたときや、DOM の hashchange イベントがトリガーされたときです。
イベント: 'will-prevent-unload'
戻り値:
eventEvent
beforeunload イベントハンドラがページのアンロードをキャンセルしようとしたときに発行されます。
event.preventDefault() を呼ぶと、beforeunload イベントハンドラが無視され、 ページをアンロードできます。
const{BrowserWindow, dialog }=require('electron')
const win =newBrowserWindow({width:800,height:600})
win.webContents.on('will-prevent-unload',(event)=>{
const choice = dialog.showMessageBoxSync(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()
}
})
[!NOTE] This will be emitted for
BrowserViewsbut will not be respected - this is because we have chosen not to tie theBrowserViewlifecycle to its owning BrowserWindow should one exist per the specification.
イベント: 'render-process-gone'
戻り値:
eventEventdetailsRenderProcessGoneDetails
renderer processが予期せず消えたときに発生します。 プロセスがクラッシュした場合やキルされた場合は正常です。
イベント: 'unresponsive'
Webページが応答しなくなるときに発生します。
イベント: 'responsive'
応答しないWebページが再び応答するようになるときに発生します。
イベント: 'destroyed'
webContents が破棄されたときに発生します。
イベント: 'input-event'
戻り値:
eventEventinputEventInputEvent
入力イベントが WebContents へ送信されたときに発生します。 See InputEvent for details.
イベント: 'before-input-event'
戻り値:
eventEventinputObject - 入力プロパティ。typestring -keyUpかkeyDown。keystring - KeyboardEvent.key と等価です。codestring - KeyboardEvent.code と等価です。isAutoRepeatboolean - KeyboardEvent.repeat と等価です。isComposingboolean - KeyboardEvent.isComposing と等価です。shiftboolean - KeyboardEvent.shiftKey と同等。controlboolean - KeyboardEvent.controlKey と同等。altboolean - KeyboardEvent.altKey と等価です。metaboolean - KeyboardEvent.metaKey と同等。locationnumber - KeyboardEvent.location と同等。modifiersstring[] - See InputEvent.modifiers.
ページ内の keydown と keyup イベントが発生する直前に発行されます。 event.preventDefault を呼ぶと、ページの keydown/keyup イベントとメニューショートカットを阻害します。
To only prevent the menu shortcuts, use setIgnoreMenuShortcuts:
const{ app,BrowserWindow}=require('electron')
app.whenReady().then(()=>{
const win =newBrowserWindow({width:800,height:600})
win.webContents.on('before-input-event',(event, input)=>{
// Enable application menu keyboard shortcuts when Ctrl/Cmd are down.
win.webContents.setIgnoreMenuShortcuts(!input.control&&!input.meta)
})
})
Event: 'before-mouse-event'
戻り値:
eventEventmouseMouseInputEvent
Emitted before dispatching mouse events in the page.
Calling event.preventDefault will prevent the page mouse events.
const{ app,BrowserWindow}=require('electron')
app.whenReady().then(()=>{
const win =newBrowserWindow({width:800,height:600})
win.webContents.on('before-mouse-event',(event, mouse)=>{
// Prevent mouseDown events.
if(mouse.type==='mouseDown'){
console.log(mouse)
/*
{
type: 'mouseDown',
clickCount: 1,
movementX: 0,
movementY: 0,
button: 'left',
x: 632.359375,
y: 480.6875,
globalX: 168.359375,
globalY: 193.6875
}
*/
event.preventDefault()
}
})
})
イベント: 'enter-html-full-screen'
ウインドウがHTML APIによってフルスクリーン状態に入るときに発生します。
イベント: 'leave-html-full-screen'
ウインドウがHTML APIによってフルスクリーン状態を抜けるときに発生します。
イベント: 'zoom-changed'
戻り値:
eventEventzoomDirectionstring -inかoutにできます。
ユーザーがマウスホイールを使用してズームレベルの変更を要求しているときに生成されます。
イベント: 'blur'
WebContents がフォーカスを失ったときに発生します。
イベント: 'focus'
WebContents がフォーカスを得たときに発生します。
注意として macOS でフォーカスを得るというのは WebContents がウインドウのファーストレスポンダ となることを意味するため、ウインドウ間でフォーカスを切り替えても各ウインドウのファーストレスポンダが変更されず WebContents の blur と focus の イベントはトリガされません。
WebContents の focus と blur イベントは、同じウインドウ内の異なる WebContents と BrowserView の間のフォーカス変化の検出に使用するとよいでしょう。
イベント: 'devtools-open-url'
戻り値:
eventEventurlstring - クリックまたは選択されたリンクの URL。
DevTools 内でリンクがクリックされたとき、またはコンテキストメニューでリンクに対して「新規タブで開く」が選択されたときに発行されます。
イベント: 'devtools-search-query'
戻り値:
eventEventquerystring - クエリするテキスト。
コンテキストメニューでテキストに対して「検索」が選択されたときに発生します。
イベント: 'devtools-opened'
開発者向けツールが開かれたときに発行されます。
イベント: 'devtools-closed'
開発者向けツールが閉じられたときに発行されます。
イベント: 'devtools-focused'
開発者向けツールがフォーカスされた / 開かれたときに発行されます。
イベント: 'certificate-error'
戻り値:
eventEventurlstringerrorstring - エラーコード。certificateCertificatecallbackFunctionisTrustedboolean - 証明書が信頼できるとみなされるかどうかを示す。
isMainFrameboolean
url の certificate の認証に失敗したときに発行されます。
使い方は、app の certificate-error イベント と同じです。
イベント: 'select-client-certificate'
戻り値:
eventEventurlURLcertificateListCertificate[]callbackFunctioncertificateCertificate - Must be a certificate from the given list.
クライアント証明書が要求されたときに発生します。
使い方は、app の select-client-certificate イベント と同じです。
イベント: 'login'
戻り値:
eventEventauthenticationResponseDetailsObjecturlURL
authInfoObjectisProxybooleanschemestringhoststringportIntegerrealmstring
callbackFunctionusernamestring (任意)passwordstring (optional)
webContents が Basic 認証を要求すると発生します。
使い方は、app の login イベント と同じです。
イベント: 'found-in-page'
戻り値:
eventEventresultObjectrequestIdIntegeractiveMatchOrdinalInteger - アクティブなマッチの位置。matchesInteger - マッチの個数。selectionAreaRectangle - 最初に一致した領域の座標。finalUpdateboolean
Emitted when a result is available for webContents.findInPage request.
イベント: 'media-started-playing'
メディアの再生を開始するときに発行されます。
イベント: 'media-paused'
メディアが一時停止、または再生が終了したときに発行されます。
イベント: 'audio-state-changed'
戻り値:
eventEvent<>audibleboolean - 1 つ以上のフレームまたは子のwebContentsが音声を再生している場合に true になります。
メディアの音が聴こえるように、または聴こえなくなったときに発生します。
イベント: 'did-change-theme-color'
戻り値:
eventEventcolor(string | null) - '#rrggbb' 形式のテーマカラー。 テーマカラーが設定されていないとnullです。
ページのテーマカラーが変わったときに発生します。 これは通常、メタタグを発見すると起こります。
<metaname='theme-color'content='#ff0000'>
イベント: 'update-target-url'
戻り値:
eventEventurlstring
マウスをリンクにマウスオーバーしたり、キーボードでリンクにフォーカスしたときに発行されます。
イベント: 'cursor-changed'
戻り値:
eventEventtypestringimageNativeImage (optional)scaleFloat (任意) - カスタムカーソルの拡大率。sizeSize (optional) - the size of theimage.hotspotPoint (optional) - coordinates of the custom cursor's hotspot.
カーソルの種類が変更されたときに発行されます。 type 引数は pointer, crosshair, hand, 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, m-panning-vertical, m-panning-horizontal, 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, null, drag-drop-none, drag-drop-move, drag-drop-copy, drag-drop-link, ns-no-resize, ew-no-resize, nesw-no-resize, nwse-no-resize, または default のいずれかにできます。
もし type パラメータが custom の場合、image パラメータはカスタムカーソルの NativeImage を、scale、size、hotspot はカスタムカーソルについての追加の情報を持ちます。
イベント: 'context-menu'
戻り値:
eventEventparamsObjectxInteger - x 座標。yInteger - y 座標。frameWebFrameMain | null - Frame from which the context menu was invoked. May benullif accessed after the frame has either navigated or been destroyed.linkURLstring - コンテキストメニューが呼び出されたノードを包むリンクの URL。linkTextstring - リンクに関連付けられたテキスト。 リンクのコンテンツが画像の場合は、空文字列になります。pageURLstring - コンテキストメニューが呼び出された最上位のページの URL。frameURLstring - コンテキストメニューが呼び出されたサブフレームの URL。srcURLstring - コンテキストメニューが呼び出された要素のソース URL。 ソース URL を持つ要素は、画像、オーディオ、ビデオです。mediaTypestring - コンテキストメニューが呼び出されたノードの種類です。none、image、audio、video、canvas、file、pluginになれる。hasImageContentsboolean - コンテキストメニューが空でない画像コンテンツに対して呼び出されたかどうか。isEditableboolean - コンテキストが編集可能かどうか。selectionTextstring - コンテキストメニューが呼び出されたときの選択テキスト。titleTextstring - コンテキストメニューが呼び出された選択範囲のタイトルテキスト。altTextstring - コンテキストメニューが呼び出されたときの選択範囲の代替テキスト。suggestedFilenamestring - コンテキストメニューの「別名でリンク先を保存」の選択肢でファイルを保存する際に使用するファイル名の候補。selectionRectRectangle - Rect representing the coordinates in the document space of the selection.selectionStartOffsetnumber - 選択テキストの開始位置。referrerPolicyReferrer - The referrer policy of the frame on which the menu is invoked.misspelledWordstring - もしあるならば、カーソル下のスペルミスした単語。dictionarySuggestionsstring[] -misspelledWordを置き換えるためにユーザに表示する単語の候補の配列。 単語のスペルミスがあり、スペルチェッカーが有効な場合にのみ利用できます。frameCharsetstring - メニューが呼び出されたときのフレームのテキストエンコーディング。formControlTypestring - コンテキストメニューの呼び出し元。 取りうる値はnone,button-button,field-set,input-button,input-checkbox,input-color,input-date,input-datetime-local,input-email,input-file,input-hidden,input-image,input-month,input-number,input-password,input-radio,input-range,input-reset,input-search,input-submit,input-telephone,input-text,input-time,input-url,input-week,output,reset-button,select-list,select-list,select-multiple,select-one,submit-button, およびtext-areaです。spellcheckEnabledboolean - そのコンテキストが編集可能な場合に、スペルチェックが有効かどうか。menuSourceTypestring - コンテキストメニューを呼び出した入力ソース。none,mouse,keyboard,touch,touchMenu,longPress,longTap,touchHandle,stylus,adjustSelection,adjustSelectionResetのいずれかになります。mediaFlagsObject - コンテキストメニューが呼び出されたメディア要素のフラグ。inErrorboolean - メディア要素がクラッシュしたかどうか。isPausedboolean - メディア要素が一時停止されているかどうか。isMutedboolean - メディア要素がミュートされているかどうか。hasAudioboolean - メディア要素に音声があるかどうか。isLoopingboolean - メディア要素をループ再生しているかどうか。isControlsVisibleboolean - メディア要素のコントロールが見えるかどうか。canToggleControlsboolean - メディア要素のコントロールがトグル切り替えできるかどうか。canPrintboolean - そのメディア要素が印刷できるかどうか。canSaveboolean - そのメディア要素がダウンロードできるかどうか。canShowPictureInPictureboolean - そのメディア要素がピクチャインピクチャ表示できるかどうか。isShowingPictureInPictureboolean - そのメディア要素をピクチャインピクチャ表示しているかどうか。canRotateboolean - メディア要素を回転できるかどうか。canLoopboolean - そのメディア要素をループ再生できるかどうか。
editFlagsObject - これらのフラグは、レンダラーが対応するアクションを実行できると信頼しているかどうかを示します。canUndoboolean - レンダラーがアンドゥできると信頼しているかどうか。canRedoboolean - レンダラーがリドゥできると信頼しているかどうか。canCutboolean - レンダラーがカットできると信頼しているかどうか。canCopyboolean - レンダラーがコピーできると信頼しているかどうか。canPasteboolean - レンダラーがペーストできると信頼しているかどうか。canDeleteboolean - レンダラーが削除できると信頼しているかどうか。canSelectAllboolean - レンダラーが全選択できると信頼しているかどうか。canEditRichlyboolean - レンダラーがテキストをリッチ編集できると信頼しているかどうか。
処理が必要な新しいコンテキストメニューがあるときに発行されます。
イベント: 'select-bluetooth-device'
戻り値:
eventEventdevicesBluetoothDevice[]callbackFunctiondeviceIdstring
navigator.bluetooth.requestDevice の呼び出し時に Bluetooth デバイスを選択する必要がある場合に発生します。 callback は、選択されたデバイスの deviceId オブジェクトで呼び出す必要があります。 空文字列を callback に渡すとリクエストをキャンセルします。
このイベントに対してイベントリスナーが追加されていない場合、すべての Bluetooth リクエストはキャンセルされます。
If event.preventDefault is not called when handling this event, the first available device will be automatically selected.
Bluetooth の性質上、navigator.bluetooth.requestDevice が呼び出されたときのデバイススキャンには時間がかかる場合があり、callback をデバイス ID で呼び出すか空文字列を渡してリクエストをキャンセルするまで、select-bluetooth-device は複数回発行されることがあります。
const{ app,BrowserWindow}=require('electron')
let win =null
app.whenReady().then(()=>{
win =newBrowserWindow({width:800,height:600})
win.webContents.on('select-bluetooth-device',(event, deviceList, callback)=>{
event.preventDefault()
const result = deviceList.find((device)=>{
return device.deviceName==='test'
})
if(!result){
// デバイスが見つからなかったので、もう少し待つか (例えばデバイスの
// 電源が入るまで)、コールバックを空文字列で呼び出してリクエストを
// キャンセルする必要があります。
callback('')
}else{
callback(result.deviceId)
}
})
})
イベント: 'paint'
戻り値:
detailsEvent<>textureOffscreenSharedTexture (optional) Experimental - The GPU shared texture of the frame, whenwebPreferences.offscreen.useSharedTextureistrue.
dirtyRectRectangleimageNativeImage - The image data of the whole frame.
新しいフレームが生成されたときに発生します。 Only the dirty area is passed in the buffer.
const{BrowserWindow}=require('electron')
const win =newBrowserWindow({webPreferences:{offscreen:true}})
win.webContents.on('paint',(event, dirty, image)=>{
// updateBitmap(dirty, image.toBitmap())
})
win.loadURL('https://github.com')
When using shared texture (set webPreferences.offscreen.useSharedTexture to true) feature, you can pass the texture handle to external rendering pipeline without the overhead of copying data between CPU and GPU memory, with Chromium's hardware acceleration support. This feature is helpful for high-performance rendering scenarios.
Only a limited number of textures can exist at the same time, so it's important that you call texture.release() as soon as you're done with the texture. By managing the texture lifecycle by yourself, you can safely pass the texture.textureInfo to other processes through IPC.
More details can be found in the offscreen rendering tutorial. To learn about how to handle the texture in native code, refer to offscreen rendering's code documentation..
const{BrowserWindow}=require('electron')
const win =newBrowserWindow({webPreferences:{offscreen:{useSharedTexture:true}}})
win.webContents.on('paint',async(e, dirty, image)=>{
if(e.texture){
// By managing lifecycle yourself, you can handle the event in async handler or pass the `e.texture.textureInfo`
// to other processes (not `e.texture`, the `e.texture.release` function is not passable through IPC).
awaitnewPromise(resolve=>setTimeout(resolve,50))
// You can send the native texture handle to native code for importing into your rendering pipeline.
// Read more at https://github.com/electron/electron/blob/main/shell/browser/osr/README.md
// importTextureHandle(dirty, e.texture.textureInfo)
// You must call `e.texture.release()` as soon as possible, before the underlying frame pool is drained.
e.texture.release()
}
})
win.loadURL('https://github.com')
イベント: 'devtools-reload-page'
開発者向けツールウインドウが webContents にリロードを指示したときに発行されます。
イベント: 'will-attach-webview'
戻り値:
eventEventwebPreferencesWebPreferences - The web preferences that will be used by the guest page. このオブジェクトを変更して、ゲストページの設定を調整できます。paramsRecord<string, string> - 他の<webview>パラメーター。srcURL などがこれにあたります。 このオブジェクトを変更して、ゲストページのパラメーターを調整できます。
<webview> の webContents がこの webContents に適用されようとしているときに発行されます。 event.preventDefault() を呼ぶとゲストページを破棄します。
このイベントは、 webContents の <webview> が読み込まれる前に webPreferences を設定するのに使用でき、<webview> の属性を通して設定できない設定を、設定する機能を提供します。
イベント: 'did-attach-webview'
戻り値:
eventEventwebContentsWebContents -<webview>で使われるゲスト WebContents。
<webview> がこの webContents に適用されたときに発行されます。
Event: 'console-message'
戻り値:
detailsEvent<>messagestring - Message textlevelstring - Message severity Possible values includeinfo,warning,error, anddebug.lineNumberInteger - Line number in the log sourcesourceIdstring - URL of the log sourceframeWebFrameMain - Frame that logged the message
levelInteger Deprecated - The log level, from 0 to 3. 順にverbose、info、warning、errorに対応します。messagestring Deprecated - The actual console messagelineInteger Deprecated - The line number of the source that triggered this console messagesourceIdstring Deprecated
関連付けられたウインドウがコンソールメッセージを出力すると発生します。
イベント: 'preload-error'
戻り値:
eventEventpreloadPathstringerrorError
プリロードスクリプト preloadPath がハンドルされていない例外 error を投げたときに発行されます。
イベント: 'ipc-message'
戻り値:
eventIpcMainEventchannelstring...argsany[]
レンダラープロセスが ipcRenderer.send() を介して非同期メッセージを送信したときに発生します。
See also webContents.ipc, which provides an IpcMain-like interface for responding to IPC messages specifically from this WebContents.
イベント: 'ipc-message-sync'
戻り値:
eventIpcMainEventchannelstring...argsany[]
レンダラープロセスが ipcRenderer.sendSync() を介して同期メッセージを送信したときに発生します。
See also webContents.ipc, which provides an IpcMain-like interface for responding to IPC messages specifically from this WebContents.
イベント: 'preferred-size-changed'
戻り値:
eventEventpreferredSizeSize - スクロールなしでドキュメントのレイアウトを格納するのに必要な最小サイズ。
WebContents の優先サイズが変更された場合に発生します。
このイベントは、webPreferences で enablePreferredSizeMode が true に設定されている場合にのみ発生します。
イベント: 'frame-created'
戻り値:
eventEventdetailsObjectframeWebFrameMain | null - The created frame. May benullif accessed after the frame has either navigated or been destroyed.
mainFrame、<iframe>、ネストした <iframe> がページ内に読み込まれると発生します。
インスタンスメソッド
contents.loadURL(url[, options])
urlstring
戻り値 Promise<void> - ページ読み込みが完了した時 (did-finish-load を参照) に解決され、ページの読み込みに失敗した時 (did-fail-load を参照) に拒否される Promise。 無操作拒否ハンドラーが既にアタッチされているため、未処理の拒否エラーは回避されます。
ウインドウ内に url を読み込みます。 url は、http:// や file:// のようなプロトコルの接頭子を含まなければなりません。 HTTP キャッシュをバイパスする必要があるロードの場合は、pragma ヘッダを使用してそれを実現します。
const win =newBrowserWindow()
const options ={extraHeaders:'pragma: no-cache\n'}
win.webContents.loadURL('https://github.com', options)
contents.loadFile(filePath[, options])
filePathstring
戻り値 Promise<void> - ページ読み込みが完了した時 (did-finish-load を参照) に解決され、ページの読み込みに失敗した時 (did-fail-load を参照) に拒否される Promise。
指定されたファイルをウインドウにロードします。filePath は、アプリケーションのルートを基準にした HTML ファイルへのパスにする必要があります。 たとえば以下のようなアプリの構造において、
| root
| - package.json
| - src
| - main.js
| - index.html
このようなコードが必要です。
const win =newBrowserWindow()
win.loadFile('src/index.html')
contents.downloadURL(url[, options])
urlstring
ナビゲーションなしで url のリソースのダウンロードを初期化します。 session の will-download イベントが発生します。
contents.getURL()
戻り値 string - 現在のウェブページの URL。
const{BrowserWindow}=require('electron')
const win =newBrowserWindow({width:800,height:600})
win.loadURL('https://github.com').then(()=>{
const currentURL = win.webContents.getURL()
console.log(currentURL)
})
contents.getTitle()
戻り値 string - 現在のウェブページのタイトル。
contents.isDestroyed()
戻り値 boolean - ウェブページが破棄されているかどうか。
contents.close([opts])
optsObject (任意)waitForBeforeUnloadboolean - true であれば、ページを閉じる前にbeforeunloadイベントを発生させます。 ページのアンロードが阻害された場合、WebContents は閉じられません。will-prevent-unloadはページがアンロードを阻害するように要求したときに発生します。
ウェブコンテンツが window.close() を呼ばれたときのように、ページを閉じます。
ページが正常に閉じられた場合 (すなわち、ページによってアンロードが妨げられなかった場合、または waitForBeforeUnload が false や未指定の場合)、WebContents は破棄され、使用できなくなります。 また destroyed イベントが発生します。
contents.focus()
ウェブページにフォーカスします。
contents.isFocused()
戻り値 boolean - ウェブページがフォーカスされているかどうか。
contents.isLoading()
戻り値 boolean - ウェブページがまだリソースを読み込んでいるかどうか。
contents.isLoadingMainFrame()
戻り値 boolean - メインフレーム (iframe やフレーム内のフレームだけではない) がまだ読み込んでいるかどうか。
contents.isWaitingForResponse()
戻り値 boolean - ウェブページが、ページのメインリソースからの最初の応答を待機しているかどうか。
contents.stop()
保留中のナビゲーションを停止します。
contents.reload()
現在のページを再読み込みします。
contents.reloadIgnoringCache()
現在のページを、キャッシュを無視して再読み込みします。
contents.canGoBack() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
戻り値 boolean - ブラウザが前のウェブページへ戻れるかどうか。
Deprecated: Should use the new contents.navigationHistory.canGoBack API.
contents.canGoForward() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
戻り値 boolean - ブラウザが次のウェブページへ進めるかどうか。
Deprecated: Should use the new contents.navigationHistory.canGoForward API.
contents.canGoToOffset(offset) 非推奨
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
offsetInteger
戻り値 boolean - offset 番目のウェブページへ行けるかどうか。
Deprecated: Should use the new contents.navigationHistory.canGoToOffset API.
contents.clearHistory() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
ナビゲーション履歴を消去します。
Deprecated: Should use the new contents.navigationHistory.clear API.
contents.goBack() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
ブラウザを前のページへ戻させます。
Deprecated: Should use the new contents.navigationHistory.goBack API.
contents.goForward() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
ブラウザを次のページへ進めさせます。
Deprecated: Should use the new contents.navigationHistory.goForward API.
contents.goToIndex(index) Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
indexInteger
ブラウザを指定した絶対ウェブページインデックスへナビゲーションします。
非推奨: 新しい contents.navigationHistory.goToIndex API を使用するようにしてください。
contents.goToOffset(offset) 非推奨
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
offsetInteger
現在のエントリから指定したオフセットへナビゲーションします。
非推奨: 新しい contents.navigationHistory.goToOffset API を使用するようにしてください。
contents.isCrashed()
戻り値 boolean - レンダラープロセスがクラッシュしたかどうか。
contents.forcefullyCrashRenderer()
このwebContents を現在ホスティングしているレンダラープロセスを強制終了します。 これにより、 reason=kill || reason=crashed である、render-process-gone イベントが発生します。 レンダラープロセスを共有しているWebContents の中には、このメソッドを呼び出すと、他のウェブコンテンツのホストプロセスがクラッシュする場合がありますのでご注意ください。
メソッドを呼び出した直後にこの reload() を呼び出すと、新しいプロセスでリロードが発生します。 これは、このプロセスが不安定または使用不可の場合、例えば unresponsive イベントから回復する際に使用されるべきです。
const win =newBrowserWindow()
win.webContents.on('unresponsive',async()=>{
const{ response }=await dialog.showMessageBox({
message:'App X has become unresponsive',
title:'Do you want to try forcefully reloading the app?',
buttons:['OK','Cancel'],
cancelId:1
})
if(response ===0){
win.webContents.forcefullyCrashRenderer()
win.webContents.reload()
}
})
contents.setUserAgent(userAgent)
userAgentstring
このウェブページのユーザエージェントをオーバーライドします。
contents.getUserAgent()
戻り値 string - このウェブページのユーザエージェント。
contents.insertCSS(css[, options])
cssstring
戻り値 Promise<string> - 挿入された CSS のキーで解決される Promise。後で contents.removeInsertedCSS(key) を使用して CSS を削除するために使用できます。
現在のウェブページに CSS を挿入し、挿入されたスタイルシートの一意なキーを返します。
const win =newBrowserWindow()
win.webContents.on('did-finish-load',()=>{
win.webContents.insertCSS('html, body { background-color: #f00; }')
})
contents.removeInsertedCSS(key)
keystring
戻り値 Promise<void> - 削除に成功すると解決されます。
現在のウェブページから挿入された CSS を削除します。 スタイルシートは contents.insertCSS(css) から返されるキーで識別されます。
const win =newBrowserWindow()
win.webContents.on('did-finish-load',async()=>{
const key =await win.webContents.insertCSS('html, body { background-color: #f00; }')
win.webContents.removeInsertedCSS(key)
})
contents.executeJavaScript(code[, userGesture])
codestringuserGestureboolean (任意) - 省略値はfalse。
戻り値 Promise<any> - 実行されたコードの結果で resolve する Promise。コードの結果が reject な Promise である場合は reject な Promise。
ページ内の code を評価します。
ブラウザウインドウでは、requestFullScreen のような、いくつかの HTML API は、ユーザからのジェスチャーでのみ呼び出されます。 userGesture を true にセットすることでこの制限がなくなります。
コードの実行は、ウェブページの読み込みが停止するまで中断されます。
const win =newBrowserWindow()
win.webContents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())',true)
.then((result)=>{
console.log(result)// fetch 呼び出しから来た JSON オブジェクトになります。
})
contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])
worldIdInteger - JavaScript を実行するワールドの ID。0はデフォルトのワールドで、999は Electron のcontextIsolation機能で使用されるワールドです。 任意の整数を指定できます。scriptsWebSource[]userGestureboolean (任意) - 省略値はfalse。
戻り値 Promise<any> - 実行されたコードの結果で resolve する Promise。コードの結果が reject な Promise である場合は reject な Promise。
executeJavaScript のように動きますが、 scripts はイソレートコンテキスト内で評価します。
contents.setIgnoreMenuShortcuts(ignore)
ignoreboolean
この WebContents がフォーカスされている間、アプリケーションのメニューショートカットを無視します。
contents.setWindowOpenHandler(handler)
-
handlerFunction<WindowOpenHandlerResponse>detailsObjecturlstring -window.open()に渡されて 解決された URL。 例えばwindow.open('foo')でウインドウを開くと、これはhttps://the-origin/the/current/path/fooのようになります。frameNamestring -window.open()で指定されたウインドウ名featuresstring -window.open()で指定されたウインドウ機能のカンマ区切りリスト。dispositionstring -default、foreground-tab、background-tab、new-window、otherにできます。referrerReferrer - The referrer that will be passed to the new window. Referrer のポリシーに依存しているので、Referrerヘッダを送信されるようにしてもしなくてもかまいません。postBodyPostBody (任意) - 新しいウィンドウに送信する POST データと、それにセットする適切なヘッダ。 送信する POST データが無い場合、値はnullになります。 これはtarget=_blankを設定したフォームによってウィンドウが作成されている場合にのみセットされます。
戻り値
WindowOpenHandlerResponse-{ action: 'deny' }をセットすると新規ウインドウの作成をキャンセルします。{ action: 'allow' }を返すと新規ウインドウが作成されます。 null、undefined、規定の 'action' の値を持たないオブジェクトといった認識されない値を返すと、コンソールエラーになり、{action: 'deny'}を返すのと同じ効果となります。
window.open()、target="_blank" のリンク、リンクのシフトクリック、<form target="_blank"> のフォーム送信などによりレンダラーが新しいウインドウを要求すると、ウインドウ作成前に呼び出されます。 詳細や did-create-window と併せた使用方法については window.open() をご参照ください。
以下の例では、新規 BrowserWindow の作成プロセスをカスタマイズして、代わりにメインウィンドウにアタッチされる BrowserView にする方法を示します。
const{BrowserView,BrowserWindow}=require('electron')
const mainWindow =newBrowserWindow()
mainWindow.webContents.setWindowOpenHandler((details)=>{
return{
action:'allow',
createWindow:(options)=>{
const browserView =newBrowserView(options)
mainWindow.addBrowserView(browserView)
browserView.setBounds({x:0,y:0,width:640,height:480})
return browserView.webContents
}
}
})
contents.setAudioMuted(muted)
mutedboolean
現在のウェブページのオーディオをミュートします。
contents.isAudioMuted()
戻り値 boolean - このページがミュートされているかどうか。
contents.isCurrentlyAudible()
戻り値 boolean - 音声が現在再生中かどうか。
contents.setZoomFactor(factor)
factorDouble - 拡大率。省略値は 1.0 です。
指定の拡大率に変更します。 拡大率は百分率なので、300% = 3.0 です。
拡大率は 0.0 より大きい必要があります。
contents.getZoomFactor()
戻り値 number - 現在の拡大率。
contents.setZoomLevel(level)
levelnumber - 拡大レベル。
指定レベルに拡大レベルを変更します。 原寸は 0 で、各増減分はそれぞれ 20% ずつの拡大または縮小を表し、デフォルトで元のサイズの 300% から 50% までに制限されています。 この式は scale := 1.2 ^ level です。
[!NOTE] The zoom policy at the Chromium level is same-origin, meaning that the zoom level for a specific domain propagates across all instances of windows with the same domain. ウインドウの URL が別々であれば、ウインドウごとのズームになります。
contents.getZoomLevel()
戻り値 number - 現在の拡大レベル。
contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevelnumbermaximumLevelnumber
戻り値 Promise<void>
ピンチによる拡大レベルの最大値と最小値を設定します。
[!NOTE] Visual zoom is disabled by default in Electron. 再び有効にする場合は以下を呼び出します。
const win =newBrowserWindow()
win.webContents.setVisualZoomLevelLimits(1,3)
contents.undo()
ウェブページの undo 編集コマンドを実行します。
contents.redo()
ウェブページの redo 編集コマンドを実行します。
contents.cut()
ウェブページの cut 編集コマンドを実行します。
contents.copy()
ウェブページの copy 編集コマンドを実行します。
contents.centerSelection()
ウェブページでの現在の選択テキストを中央揃えにします。
contents.copyImageAt(x, y)
xIntegeryInteger
指定した位置の画像をクリップボードにコピーします。
contents.paste()
ウェブページの paste 編集コマンドを実行します。
contents.pasteAndMatchStyle()
ウェブページの pasteAndMatchStyle 編集コマンドを実行します。
contents.delete()
ウェブページの delete 編集コマンドを実行します。
contents.selectAll()
ウェブページの selectAll 編集コマンドを実行します。
contents.unselect()
ウェブページの unselect 編集コマンドを実行します。
contents.scrollToTop()
現在の webContents を一番上までスクロールします。
contents.scrollToBottom()
現在の webContents を一番下までスクロールします。
contents.adjustSelection(options)
フォーカスされているフレーム内の現在のテキスト選択の始点と終点を、指定の量だけ調整します。 負の値を指定すると選択範囲はドキュメントの先頭方向に、正の値を指定すると選択範囲はドキュメントの末尾方向に移動します。
サンプル:
const win =newBrowserWindow()
// 選択範囲の開始を 1 文字先に、
// 選択範囲の終了を 5 文字先に調節します。
win.webContents.adjustSelection({start:1,end:5})
// 選択範囲の開始を 2 文字先に、
// 選択範囲の終了を 3 文字手前に調節します。
win.webContents.adjustSelection({start:2,end:-3})
win.webContents.adjustSelection({ start: 1, end: 5 }) を呼び出すと
以前:
テキスト選択の調整前の画像適用後:
テキスト選択の調整後の画像contents.replace(text)
textstring
ウェブページの replace 編集コマンドを実行します。
contents.replaceMisspelling(text)
textstring
ウェブページの replaceMisspelling 編集コマンドを実行します。
contents.insertText(text)
textstring
戻り値 Promise<void>
フォーカスされた要素に text を挿入します。
contents.findInPage(text[, options])
textstring - 検索するコンテンツ。空にしてはいけません。
戻り値 Integer - リクエストに使われたリクエスト ID。
ウェブページ内の text のすべてのマッチを探すリクエストを開始します。 リクエストの結果は found-in-page イベントを読むことで取得できます。
contents.stopFindInPage(action)
actionstring -webContents.findInPageリクエストを終了する際に行うアクションを指定します。clearSelection- 選択を消去する。keepSelection- その選択を通常の選択に変換する。activateSelection- 選択ノードをフォーカスして、クリックする。
指定された action で、webContents の findInPage リクエストを停止します。
const win =newBrowserWindow()
win.webContents.on('found-in-page',(event, result)=>{
if(result.finalUpdate) win.webContents.stopFindInPage('clearSelection')
})
const requestId = win.webContents.findInPage('api')
console.log(requestId)
contents.capturePage([rect, opts])
rectRectangle (optional) - The area of the page to be captured.optsObject (任意)stayHiddenboolean (任意) - ページを表示せずに非表示のままにします。 省略値はfalseです。stayAwakeboolean (任意) - システムをスリープさせずに、起きたままにします。 省略値はfalseです。
戻り値 Promise<NativeImage> - NativeImage を解決します
rect 内のページのスナップショットをキャプチャします。 rect を省略すると、表示されているページ全体をキャプチャします。 ブラウザーウインドウが非表示でもキャプチャ回数がゼロではない場合、ページは表示されていると見なされます。 ページを非表示のままにする場合は、stayHidden を true に設定していることを確認してください。
contents.isBeingCaptured()
Returns boolean - このページがキャプチャされているかどうか。 It returns true when the capturer count is greater than 0.
contents.getPrintersAsync()
システムプリンタのリストを取得します。
Returns Promise<PrinterInfo[]> - Resolves with a PrinterInfo[]
contents.print([options], [callback])
callbackFunction (任意)successboolean - 印刷呼び出しの成功を示します。failureReasonstring - 印刷に失敗した場合に呼び戻されるエラーの説明です。
カスタムの pageSize を渡すと、Chromium は width_microns と height_microns それぞれのプラットフォーム固有の最小値を検証しようとします。 幅、高さともに最低 353 ミクロンでなければなりませんが、オペレーティングシステムによってはそれ以上になることがあります。
ウインドウのウェブページを印刷します。 silent が true にセットされたとき、deviceName が空で印刷のデフォルト設定があれば、Electron はシステムのデフォルトプリンタを選択します。
Some possible failureReasons for print failure include:
- "Invalid printer settings"
- "Print job canceled"
- "Print job failed"
page-break-before: always; CSS スタイルを使用して、強制的に改ページして印刷できます。
使用例:
const win =newBrowserWindow()
const options ={
silent:true,
deviceName:'My-Printer',
pageRanges:[{
from:0,
to:1
}]
}
win.webContents.print(options,(success, errorType)=>{
if(!success)console.log(errorType)
})
contents.printToPDF(options)
戻り値 Promise<Buffer> - 生成された PDF データで実行されます。
そのウインドウのウェブページを PDF として印刷します。
@page CSS ルールがウェブページ内で使われている場合、landscape は無視されます。
これは webContents.printToPDF の例です。
const{ app,BrowserWindow}=require('electron')
const fs =require('node:fs')
const os =require('node:os')
const path =require('node:path')
app.whenReady().then(()=>{
const win =newBrowserWindow()
win.loadURL('https://github.com')
win.webContents.on('did-finish-load',()=>{
// Use default printing options
const pdfPath = path.join(os.homedir(),'Desktop','temp.pdf')
win.webContents.printToPDF({}).then(data=>{
fs.writeFile(pdfPath, data,(error)=>{
if(error)throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error=>{
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
})
})
詳細は Page.printToPdf をご覧ください。
contents.addWorkSpace(path)
pathstring
指定したパスをデベロッパー ツールのワークスペースに追加します。 デベロッパー ツールが生成された後で使用しなければいけません。
const{BrowserWindow}=require('electron')
const win =newBrowserWindow()
win.webContents.on('devtools-opened',()=>{
win.webContents.addWorkSpace(__dirname)
})
contents.removeWorkSpace(path)
pathstring
開発者向けツールのワークスペースから指定したパスを削除します。
contents.setDevToolsWebContents(devToolsWebContents)
devToolsWebContentsWebContents
devToolsWebContents を開発者向けツールを表示するターゲット WebContents として使用します。
devToolsWebContents はナビゲーションを行ってはいけません。また、コール後に他の目的に使用することはできません。
デフォルトでは、Electron は開発者が制御を非常に制限したネイティブビューを持つ内部 WebContents を作成することによって開発者向けツールを管理します。 setDevToolsWebContents メソッドでは、開発者は任意の WebContents を使用して、BrowserWindow、BrowserView、<webview> タグなどの開発者向けツールを表示できます。
開発者向けツールを閉じても devToolsWebContents は破棄されないことに注意してください。 devToolsWebContents を破棄するのは呼び出し元の責任です。
<webview> タグ内で開発者向けツールを表示する例:
<html>
<head>
<styletype="text/css">
*{margin:0;}
#browser{height:70%;}
#devtools{height:30%;}
</style>
</head>
<body>
<webviewid="browser"src="https://github.com"></webview>
<webviewid="devtools"src="about:blank"></webview>
<script>
const{ ipcRenderer }=require('electron')
constemittedOnce=(element, eventName)=>newPromise(resolve=>{
element.addEventListener(eventName,event=>resolve(event),{once:true})
})
const browserView =document.getElementById('browser')
const devtoolsView =document.getElementById('devtools')
const browserReady =emittedOnce(browserView,'dom-ready')
const devtoolsReady =emittedOnce(devtoolsView,'dom-ready')
Promise.all([browserReady, devtoolsReady]).then(()=>{
const targetId = browserView.getWebContentsId()
const devtoolsId = devtoolsView.getWebContentsId()
ipcRenderer.send('open-devtools', targetId, devtoolsId)
})
</script>
</body>
</html>
// Main process
const{ ipcMain, webContents }=require('electron')
ipcMain.on('open-devtools',(event, targetContentsId, devtoolsContentsId)=>{
const target = webContents.fromId(targetContentsId)
const devtools = webContents.fromId(devtoolsContentsId)
target.setDevToolsWebContents(devtools)
target.openDevTools()
})
BrowserWindow 内で開発者向けツールを表示する例:
const{ app,BrowserWindow}=require('electron')
let win =null
let devtools =null
app.whenReady().then(()=>{
win =newBrowserWindow()
devtools =newBrowserWindow()
win.loadURL('https://github.com')
win.webContents.setDevToolsWebContents(devtools.webContents)
win.webContents.openDevTools({mode:'detach'})
})
contents.openDevTools([options])
開発者向けツールを開く。
contents が <webview> タグである場合、デフォルトでは mode が detach になり、空の mode を明示的に渡すと最後に使用されたドックステートを使用して強制的に実行されます。
Windows では、Windows コントロールオーバーレイが有効になっているとデベロッパー ツールは mode: 'detach' で開かれます。
contents.closeDevTools()
開発者向けツールを閉じる。
contents.isDevToolsOpened()
戻り値 boolean - デベロッパー ツールが開かれているかどうか。
contents.isDevToolsFocused()
戻り値 boolean - デベロッパー ツールがフォーカスされているかどうか。
contents.getDevToolsTitle()
戻り値 string - デベロッパー ツールウインドウのタイトル。 This will only be visible if DevTools is opened in undocked or detach mode.
contents.setDevToolsTitle(title)
titlestring
デベロッパー ツールのウインドウのタイトルを title に変更します。 これはデベロッパー ツールが undocked または detach モードで開かれている場合にのみ表示されます。
contents.toggleDevTools()
開発者向けツールをトグル切り替えします。
contents.inspectElement(x, y)
xIntegeryInteger
(x, y) の位置の要素の検査を開始します。
contents.inspectSharedWorker()
共有ワーカーコンテキストの開発者向けツールを開きます。
contents.inspectSharedWorkerById(workerId)
workerIdstring
ID に基づいて共有ワーカーのインスペクターを起動します。
contents.getAllSharedWorkers()
戻り値 SharedWorkerInfo[] - すべての共有ワーカーに関する情報。
contents.inspectServiceWorker()
サービスワーカコンテキストの開発者向けツールを開きます。
contents.send(channel, ...args)
channelstring...argsany[]
引数と共に、channel を介してレンダラープロセスに非同期メッセージを送信します。 引数は postMessage と同じように 構造化複製アルゴリズム によってシリアライズされるため、プロトタイプチェーンは含まれません。 関数、Promise、Symbol、WeakMap、WeakSet の送信は、例外が送出されます。
DOM オブジェクトや特殊な Electron オブジェクトなど、非標準の JavaScript 型を送信すると例外が発生します。
For additional reading, refer to Electron's IPC guide.
contents.sendToFrame(frameId, channel, ...args)
frameIdInteger | [number, number] - 送信先のフレームの ID、またはフレームがメインフレームと異なるプロセスにある場合に[processId, frameId]の組み合わせを指定します。channelstring...argsany[]
引数と共に、channel を介してレンダラープロセス内の指定のフレームに非同期メッセージを送信します。 引数は postMessage と同じように 構造化複製アルゴリズム によってシリアライズされるため、プロトタイプチェーンは含まれません。 関数、Promise、Symbol、WeakMap、WeakSet の送信は、例外が送出されます。
注意: DOM オブジェクトや特殊な Electron オブジェクトなど、非標準の JavaScript 型を送信すると例外が発生します。
レンダラープロセスは ipcRenderer モジュールで channel を聞いてメッセージを処理できます。
与えられたレンダラーコンテキストの frameId を取得したい場合は、webFrame.routingId の値を使用します。 以下は例です。
// レンダラープロセス内
console.log('My frameId is:',require('electron').webFrame.routingId)
メインプロセス内の受信した IPC メッセージすべてから frameId を読み取ることもできます。
// メインプロセス内
ipcMain.on('ping',(event)=>{
console.info('Message came from frameId:', event.frameId)
})
contents.postMessage(channel, message, [transfer])
channelstringmessageanytransferMessagePortMain[] (任意)
Send a message to the renderer process, optionally transferring ownership of zero or more MessagePortMain objects.
転送された MessagePortMain オブジェクトは、レンダラープロセスで発生したイベントの ports プロパティにアクセスすれば利用できます。 レンダラーに着くと、それらはネイティブの DOM MessagePort オブジェクトになります。
以下がその例です。
// メインプロセス
const win =newBrowserWindow()
const{ port1, port2 }=newMessageChannelMain()
win.webContents.postMessage('port',{message:'hello'},[port1])
// レンダラープロセス
ipcRenderer.on('port',(e, msg)=>{
const[port]= e.ports
// ...
})
contents.enableDeviceEmulation(parameters)
parametersObjectscreenPositionstring - エミュレートする画面の種類を以下から指定します (省略値:desktop)。desktop- デスクトップ画面タイプ。mobile- モバイル画面タイプ。
screenSizeSize - Set the emulated screen size (screenPosition == mobile).viewPositionPoint - Position the view on the screen (screenPosition == mobile) (default:{ x: 0, y: 0 }).deviceScaleFactorInteger - デバイスの拡大率の設定 (ゼロなら元々のデバイスの拡大率) (省略値:0)。viewSizeSize - Set the emulated view size (empty means no override)scaleFloat - 有効なスペース内のエミュレートするビューの拡大率 (表示モードには合わせません) (省略値:1)。
与えられた引数でデバイスのエミュレートを有効にします
contents.disableDeviceEmulation()
webContents.enableDeviceEmulation で有効にしたデバイスのエミュレートを向こうにします。
contents.sendInputEvent(inputEvent)
inputEventMouseInputEvent | MouseWheelInputEvent | KeyboardInputEvent
入力 event をページに送ります。
[!NOTE] The
BrowserWindowcontaining the contents needs to be focused forsendInputEvent()to work.
contents.beginFrameSubscription([onlyDirty ,]callback)
onlyDirtyboolean (任意) - 省略値はfalse。callbackFunctionimageNativeImagedirtyRectRectangle
プレゼンテーションイベントとキャプチャされたフレームの監視を開始し、プレゼンテーションイベントがあれば、callbabck が callback(image, dirtyRect) で呼ばれます。
image はキャプチャされたフレームを格納する NativeImage のインスタンスです。
dirtyRect は 再描画されたページの部分を示す x, y, width, height プロパティのオブジェクトです。 もし onlyDirty が true にセットされている場合、image は再描画された領域だけを含みます。 onlyDirty defaults to false.
contents.endFrameSubscription()
フレームプレゼンテーションイベントの監視を終了します。
contents.startDrag(item)
itemObjectfilestring - ドラッグされているファイルのパス。filesstring[] (任意) - ドラッグされている複数ファイルのパス。 (filesはfileフィールドより優先されます)iconNativeImage | string - The image must be non-empty on macOS.
現在の D&D 操作のドラッグアイテムに item をセットします。file はドラッグされるファイルへの絶対パスで、icon はドラッグするときにカーソルの下に表示される画像です。
contents.savePage(fullPath, saveType)
fullPathstring - ファイルの絶対パス。saveTypestring - 保存のタイプを指定します。HTMLOnly- ページの HTML だけを保存する。HTMLComplete- 完全な HTML ページを保存する。MHTML- MHTML として完全な HTML ページを保存する。
戻り値 Promise<void> - ページが保存された場合に実行されます。
const{BrowserWindow}=require('electron')
const win =newBrowserWindow()
win.loadURL('https://github.com')
win.webContents.on('did-finish-load',async()=>{
win.webContents.savePage('/tmp/test.html','HTMLComplete').then(()=>{
console.log('Page was saved successfully.')
}).catch(err=>{
console.log(err)
})
})
contents.showDefinitionForSelection() macOS
ページ上の選択された単語を検索するポップアップ辞書を表示します。
contents.isOffscreen()
戻り値 boolean - オフスクリーンレンダリング が有効にされているかどうかを示す。
contents.startPainting()
もし オフスクリーンレンダリング が有効かつ描画中でなければ、描画を開始します。
contents.stopPainting()
もし オフスクリーンレンダリング が有効かつ描画中であれば、描画を終了します。
contents.isPainting()
戻り値 boolean - もし オフスクリーンレンダリング が有効であれば、現在描画中かどうかを返します。
contents.setFrameRate(fps)
fpsInteger
もし オフスクリーンレンダリング が有効であれば指定された数字にフレームレートをセットします。 1 から 240 の値のみを受け取ります。
contents.getFrameRate()
戻り値 Boolean - もし オフスクリーンレンダリング が有効であれば、現在のフレームレートを返します。
contents.invalidate()
このウェブコンテンツが入っているウインドウの完全な再描画をスケジュールします。
もし オフスクリーンレンダリング が有効であれば、フレームを無効にし、'paint' を通して新しいフレームを生成します。
contents.getWebRTCIPHandlingPolicy()
戻り値 string - WebRTC IP ハンドリングポリシーを返します。
contents.setWebRTCIPHandlingPolicy(policy)
policystring - WebRTC IP ハンドリングポリシーを指定します。default- ユーザの公開IPとローカルIPを公開します。 これはデフォルトの動作です。 このポリシーが使用されるとき、WebRTC には、すべてのインターフェースを列挙し、それらを結合して公開インターフェースを検出する権利があります。default_public_interface_only- ユーザの公開IPを公開しますが、ユーザのローカルIPは公開しません。 このポリシーが使用されるとき、WebRTC は HTTP が使用するデフォルトのルートのみを使用する必要があります。 これはどのローカルアドレスも公開しません。default_public_and_private_interfaces- ユーザの公開IPとローカルIPを公開します。 このポリシーが使用されるとき、WebRTC は HTTP が使用するデフォルトのルートのみを使用する必要があります。 これは関連するデフォルトのプライベートアドレスも公開します。 デフォルトルートは、マルチホームのエンドポイント上で OS によって選択されたルートです。disable_non_proxied_udp- パブリック IP やローカル IP を非公開にします。 このポリシーが使用される WebRTC は、プロキシサーバーが UDP をサポートしていない限り、TCP を使用してピアまたはサーバーに接続する必要があります。
WebRTC IP ハンドリングポリシーを設定すると、WebRTC を介して公開される IP を制御できます。 See BrowserLeaks for more details.
contents.getWebRTCUDPPortRange()
戻り値 Object:
minInteger - WebRTC が使用すべき最小の UDP ポート番号。maxInteger - WebRTC が使用すべき最大の UDP ポート番号。
デフォルトのこの値は { min: 0, max: 0 } で、これは UDP ポートの範囲に制限を適用しないものです。
contents.setWebRTCUDPPortRange(udpPortRange)
udpPortRangeObjectminInteger - WebRTC が使用すべき最小の UDP ポート番号。maxInteger - WebRTC が使用すべき最大の UDP ポート番号。
WebRTC UDP ポート範囲を設定すると、WebRTC で使用される UDP ポートの範囲を制限できます。 既定では、ポート範囲は制限されていません。
[!NOTE] To reset to an unrestricted port range this value should be set to
{ min: 0, max: 0 }.
contents.getMediaSourceId(requestWebContents)
requestWebContentsWebContents - id が登録されるウェブコンテンツ。
Returns string - WebContents ストリームの識別子。 この識別子は tab の chromeMediaSource を使う navigator.mediaDevices.getUserMedia で利用できます。 この識別子は登録されたウェブコンテンツのみにおいて、10 秒間だけ有効です。
contents.getOSProcessId()
戻り値 Integer - 関連するレンダラープロセスのオペレーティングシステムの pid。
contents.getProcessId()
戻り値 Integer - 関連するレンダラーの Chromium 内部の pid。 フレーム特有のナビゲーションイベント (did-frame-navigate など) で渡される frameProcessId と比較できます。
contents.takeHeapSnapshot(filePath)
filePathstring - 出力ファイルのパス
戻り値 Promise<void> - スナップショットの作成が成功したかどうかを示します。
V8 ヒープのスナップショットを撮り、それを filePath に保存します。
contents.getBackgroundThrottling()
戻り値 boolean - ページがバックグラウンドになったときに、この WebContents がアニメーションやタイマーを抑制するかどうか。 これは Page Visibility API にも影響を与えます。
contents.setBackgroundThrottling(allowed)
History
allowedboolean
ページがバックグラウンドになったときにこの WebContents がアニメーションとタイマーを抑制するかどうかを制御します。 これは Page Visibility API にも影響を与えます。
contents.getType()
Returns string - webContents の型。 Can be backgroundPage, window, browserView, remote, webview or offscreen.
contents.setImageAnimationPolicy(policy)
policystring -animate、animateOnceかnoAnimationにできます。
この webContents の画像アニメーションポリシーを設定します。 このポリシーは 新しく読み込まれた 画像にのみ適用され、現在アニメーションを行っている既存の画像は影響を受けません。 これは Chromium の既知の制限で、img.src = img.src とすることで画像のアニメーションを強制的に再計算させられます。この場合、ネットワークトラフィックは発生しませんが、アニメーションポリシーが更新されます。
This corresponds to the animationPolicy accessibility feature in Chromium.
インスタンスプロパティ
contents.ipc 読み出し専用
An IpcMain scoped to just IPC messages sent from this WebContents.
ipcRenderer.send、ipcRenderer.sendSync や ipcRenderer.postMessage で送信した IPC メッセージは以下の順番で伝達されます。
contents.on('ipc-message')contents.mainFrame.on(channel)contents.ipc.on(channel)ipcMain.on(channel)
invoke で登録されたハンドラは以下の順番で確認されます。 最初に定義されているものが呼び出され, 以降は無視されます。
contents.mainFrame.handle(channel)contents.handle(channel)ipcMain.handle(channel)
WebContents で登録されたハンドラやイベントリスナーは、子フレームを含む任意のフレームから送信された IPC メッセージを受信します。 ほとんどの場合、メインフレームだけが IPC メッセージを送信できます。 しかし、nodeIntegrationInSubFrames オプションが有効の場合、子フレームも IPC メッセージを送信できます。 その場合、ハンドラは IPC イベントの senderFrame プロパティをチェックし、メッセージが期待のフレームから送られていることを確認する必要があります。 Alternatively, register handlers on the appropriate frame directly using the WebFrameMain.ipc interface.
contents.audioMuted
このページをミュートするかどうかを決定する boolean プロパティ。
contents.userAgent
このウェブページのユーザーエージェントを決定する string プロパティ。
contents.zoomLevel
このウェブコンテンツのズームレベルを決定する number プロパティ。
原寸は 0 で、各増減分はそれぞれ 20% ずつの拡大または縮小を表し、デフォルトで元のサイズの 300% から 50% までに制限されています。 The formula for this is scale := 1.2 ^ level.
contents.zoomFactor
number 型のプロパティです。このウェブコンテンツのズーム率を決定します。
ズーム率は百分率のズームなので、300% = 3.0 になります。
contents.frameRate
Integer 型のプロパティです。ウェブコンテンツのフレームレートを指定された数値に設定します。 1 から 240 の値のみを受け取ります。
オフスクリーンレンダリング が有効な場合にのみ適用されます。
contents.id 読み出し専用
この WebContents の一意のIDを表す Integer。 各 ID は、この Electron アプリケーション全体のすべての WebContents インスタンス間で一意です。
contents.session 読み出し専用
A Session used by this webContents.
contents.navigationHistory 読み出し専用
この webContents で使われる NavigationHistory。
contents.hostWebContents 読み出し専用
A WebContents instance that might own this WebContents.
contents.devToolsWebContents 読み出し専用
WebContents | null 型のプロパティ。その WebContents に関連付けられたデベロッパー ツール の WebContents を表します。
[!NOTE] Users should never store this object because it may become
nullwhen the DevTools has been closed.
contents.debugger 読み出し専用
A Debugger instance for this webContents.
contents.backgroundThrottling
History
boolean 型のプロパティです。ページがバックグラウンドになったときに、この WebContents がアニメーションやタイマーを抑制するかどうかを決定します。 これは Page Visibility API にも影響を与えます。
contents.mainFrame 読み出し専用
A WebFrameMain property that represents the top frame of the page's frame hierarchy.
contents.opener 読み出し専用
WebFrameMain | null 型のプロパティで、この WebContents を開いたフレームを表します。open() あるいは target 属性を付けたリンクへナビゲートしたときの WebContents です。
contents.focusedFrame 読み出し専用
A WebFrameMain | null property that represents the currently focused frame in this WebContents. Can be the top frame, an inner <iframe>, or null if nothing is focused.