SOLFIND
Web Lens
Portal home

BrowserWindow | Electron

https://www.electronjs.org/ru/docs/latest/api/browser-window • 302 KB fetched
Open original page


BrowserWindow | Electron Перейти к основному содержанию Electron Документация API Блог Инструменты * Electron Forge * Electron Fiddle Сообщество * Управление * Примеры * Ресурсы Релизы Русский * English * Deutsch * Español * Français * 日本語 * Português * Русский * 中文 Поиск * Модули основного процесса * app * autoUpdater * BaseWindow * BrowserView * Deprecated * BrowserWindow * clipboard * contentTracing * crashReporter * desktopCapturer * dialog * globalShortcut * ImageView * inAppPurchase * ipcMain * Menu * MenuItem * MessageChannelMain * MessagePortMain * nativeImage * nativeTheme (Родная тема) * net * netLog * Notification (Оповещения) * powerMonitor * powerSaveBlocker * process * protocol * pushNotifications * safeStorage * screen * session * sharedTexture * ShareMenu * shell * systemPreferences * TouchBar * Tray * utilityProcess * webContents * WebContentsView * webFrameMain * View * Модули графического процесса * Utility Process Modules * Пользовательские DOM-элементы * Chromium и Node.js * Классы * Структуры API * * Модули основного процесса * BrowserWindow На этой странице BrowserWindow Создавайте окна браузера и управляйте ими. Process: Main Этот модуль нельзя использовать до тех пор, пока событие ready в app не будет готово к использованию. // В основном процессе. const { BrowserWindow } = require ( 'electron' ) const win = new BrowserWindow ( { width : 800 , height : 600 } ) // Загрузка удаленного URL win . loadURL ( 'https://github.com' ) // Или загрузка локального HTML файла win . loadFile ( 'index.html' ) Настройки окна ​ Класс BrowserWindow раскрывает различные способы изменения внешнего вида и поведения окон вашего приложения. For more details, see the Window Customization tutorial. Showing the window gracefully ​ When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display without a visual flash, there are two solutions for different situations. Использование события ready-to-show ​ При загрузке страницы, после отрисовки страницы будет происходить событие ready-to-show , которое будет происходить первый раз, если окно до этого еще не было показано. Окно, показанное после этого события, не будет иметь визуальной ступенчатой подгрузки: const { BrowserWindow } = require ( 'electron' ) const win = new BrowserWindow ( { show : false } ) win . once ( 'ready-to-show' , ( ) => { win . show ( ) } ) Обычно это событие происходит после события did-finish-load . Однако, страницы, включающие в себя удаленные ресурсы, могут продолжать подгружаться после происхождения события did-finish-load . Пожалуйста, обратите внимание, что использование этого события означает, что рендерер будет считаться "видимым" и отрисуется, даже если show является false. Это событие никогда не сработает, если вы используете paintWhenInitiallyHidden: false Указание значения свойства backgroundColor ​ Для больших приложений событие ready-to-show может вызываться слишком поздно, что может замедлить приложение. В этом случае рекомендуется показать окно немедленно, и использовать backgroundColor , задающий цвет фона Вашего приложения: const { BrowserWindow } = require ( 'electron' ) const win = new BrowserWindow ( { backgroundColor : '#2e2c29' } ) win . loadURL ( 'https://github.com' ) Обратите внимание, что даже для приложений, использующих ready-to-show события, всё равно рекомендуется установить backgroundColor , чтобы придать приложению более естественный вид. Приведем несколько примеров возможных значений backgroundColor : const win = new BrowserWindow ( ) win . setBackgroundColor ( 'hsl(230, 100%, 50%)' ) win . setBackgroundColor ( 'rgb(255, 145, 145)' ) win . setBackgroundColor ( '#ff00a3' ) win . setBackgroundColor ( 'blueviolet' ) For more information about these color types see valid options in win.setBackgroundColor . Родительские и дочерние окна ​ С помощью параметра parent , Вы можете создавать дочерние окна: const { BrowserWindow } = require ( 'electron' ) const top = new BrowserWindow ( ) const child = new BrowserWindow ( { parent : top } ) child . show ( ) top . show ( ) Окно child будет всегда показано поверх окна top . Модальные окна ​ A modal window is a child window that disables parent window. To create a modal window, you have to set both the parent and modal options: const { BrowserWindow } = require ( 'electron' ) const top = new BrowserWindow ( ) const child = new BrowserWindow ( { parent : top , modal : true , show : false } ) child . loadURL ( 'https://github.com' ) child . once ( 'ready-to-show' , ( ) => { child . show ( ) } ) Видимость страниц ​ API видимости страниц работает следующим образом: * На всех платформах состояние видимости отслеживает скрыто/уменьшено окно или нет. * Кроме того, на macOS, состояние видимости также отслеживает состояние перекрытия окна. Если окно перекрыто (т.е. полностью покрыто) другим окном, состояние видимости будет hidden . На других платформах состояние видимости будет hidden , только когда окно уменьшено или явно скрыто при помощи win.hide() . * Если BrowserWindow создано с show: false , первоначальное состояние видимости будет visible , несмотря на фактически скрытое окно. * Если backgroundThrottling отключено, состояние видимости останется visible , даже если окно уменьшено, закрыто или скрыто. Рекомендуется приостановить дорогостоящие операции, когда состояние видимости hidden , для того чтобы свести к минимуму потребление энергии. Платформа заметок ​ * На macOS модальные окна будут отображены в виде страниц, прикрепленных к родительскому окну. * На macOS дочерние окна будут находиться относительно родительского окна, во время передвижения родительского окна, тем временем на Windows и Linux дочерние окна не будут двигаться. * На Linux тип модального окна будет поменян в dialog . * На Linux многие среды рабочего стола не поддерживают скрытие модального окна. * На Wayland (Linux) восновном невозможно программно изменить размер окон после создания, или переместить в, перемещение, фокус, или размытие окон без ввода пользователем. If your app needs these capabilities, run it in Xwayland by appending the flag --ozone-platform=x11 . Class: BrowserWindow extends BaseWindow ​ Создавайте окна браузера и управляйте ими. Process: Main BrowserWindow является EventEmitter . Так создается новый экземпляр BrowserWindow с нативными свойствами, установленными в options . [!WARNING] Electron's built-in classes cannot be subclassed in user code. For more information, see the FAQ . new BrowserWindow([options]) ​ * options BrowserWindowConstructorOptions (optional) * webPreferences WebPreferences (опционально) - Настройки функций веб-страницы. * devTools boolean (опционально) - включает инструменты разработчика. Если значение false , нельзя будет использовать BrowserWindow.webContents.openDevTools() , чтобы открыть инструменты разработчика. По умолчанию - true . * nodeIntegration boolean (optional) - Whether node integration is enabled. По умолчанию - false . * nodeIntegrationInWorker boolean (опционально) - включает интеграцию NodeJS в веб-воркерах. По умолчанию - false . More about this can be found in Multithreading . * nodeIntegrationInSubFrames boolean (опционально) - экспериментальная опция для включения поддержки NodeJS в подфреймах, таких как iframes и дочерних окнах. Все Ваши предварительные загрузки будут загружены для каждого iframe, Вы можете использовать process.isMainFrame , чтобы определить в главном фрейме Вы или нет. * preload string (опционально) - Определяет скрипт, который будет загружен до других скриптов загружаемых в странице. Этот скрипт будет всегда иметь доступ к API NodeJS, вне зависимости включена или выключена интеграция NodeJS. Значение должно быть абсолютным путем к файлу скрипта. Когда интеграция NodeJS отключена, предварительно загруженный скрипт может повторно ввести глобальные символы NodeJS в глобальную область. See example here . * sandbox boolean (опционально) - если установлено true, то в окне будет запущена песочница, что делает ее совместимой с песочницей Chromium на уровне операционной системы, и отключает движок NodeJS. Это не тоже самое, что параметр nodeIntegration , доступные API для предзагруженных скриптов более ограничены. Default is true since Electron 20. The sandbox will automatically be disabled when nodeIntegration is set to true . Read more about the option here . * session Session (optional) - Sets the session used by the page. Вместо передачи экземпляр Session напрямую, вместо этого Вы можете также выбрать использование опции partition , которая принимает строку раздела. Когда оба session и partition определены, session будет предпочтительней. По умолчанию используется сессия по умолчанию. * partition string (опционально) - устанавливает сессию, используемую на странице в соответствии со строкой раздела сессии. Если partition начинается с persist: , страница будет использовать постоянную сессию, которая доступна всем страницам в приложении с тем же разделом . Если нет префикса persist: , страница будет использовать сессию в памяти. При присваивании одинакового раздела , разные страницы могут иметь одинаковую сессию. По умолчанию используется сессия по умолчанию. * zoomFactor number (optional) - The default zoom factor of the page, 3.0 represents 300% . По умолчанию 1.0 . * javascript boolean (optional) - Enables JavaScript support. По умолчанию - true . * webSecurity boolean (optional) - When false , it will disable the same-origin policy (usually using testing websites by people), and set allowRunningInsecureContent to true if this option has not been set by user. По умолчанию - true . * allowRunningInsecureContent boolean (optional) - Allow an https page to run JavaScript, CSS or plugins from http URLs. По умолчанию - false . * images boolean (optional) - Enables image support. По умолчанию - true . * imageAnimationPolicy string (optional) - Specifies how to run image animations (E.g. GIFs). Can be animate , animateOnce or noAnimation . По умолчанию animate . * textAreasAreResizable boolean (optional) - Make TextArea elements resizable. Default is true . * webgl boolean (optional) - Enables WebGL support. По умолчанию - true . * plugins boolean (optional) - Whether plugins should be enabled. По умолчанию - false . * experimentalFeatures boolean (optional) - Enables Chromium's experimental features. По умолчанию - false . * scrollBounce boolean (optional) macOS - Enables scroll bounce (rubber banding) effect on macOS. По умолчанию - false . * enableBlinkFeatures string (опционально) - список строк функций, разделенных запятой , которые нужно включить, например CSSVariables,KeyboardEventKey . Полный список поддерживаемых возможностей можно найти в файле RuntimeEnabledFeatures.json5 . * disableBlinkFeatures string (опционально) - Список функциональных возможностей для выключения, разделяются ',' , например CSSVariables,KeyboardEventKey . Полный список поддерживаемых возможностей можно найти в файле RuntimeEnabledFeatures.json5 . * defaultFontFamily Object (optional) - Sets the default font for the font-family. * standard string (опционально) - По умолчанию Times New Roman . * serif string (опционально) - по умолчанию Times New Roman . * sansSerif string (опционально) - По умолчанию Arial . * monospace string (опционально) - По умолчанию Courier New . * cursive string (опционально) - По умолчанию Script . * fantasy string (опционально) - По умолчанию Impact . * math string (опционально) - По умолчанию Latin Modern Math . * defaultFontSize Integer (опционально) - По умолчанию 16 . * defaultMonospaceFontSize Integer (опционально) - По умолчанию 13 . * minimumFontSize Integer (опционально) - По умолчанию 0 . * defaultEncoding string (опционально) - По умолчанию ISO-8859-1 . * backgroundThrottling boolean (опционально) - Отключать ли анимацию и таймеры, когда страница становится фоновой. Влияет на API видимости страницы . When at least one webContents displayed in a single browserWindow has disabled backgroundThrottling then frames will be drawn and swapped for the whole window and other webContents displayed by it. По умолчанию true . * offscreen Object | boolean (опционально) - рендеринг окна браузера вне экрана. По умолчанию false . See the offscreen rendering tutorial for more details. * useSharedTexture boolean (опционально) Экспериментальный - использование GPU общих текстур для ускорения отрисовки. По умолчанию false . See the offscreen rendering tutorial for more details. * sharedTexturePixelFormat string (optional) Experimental - The requested output format of the shared texture. По умолчанию argb . The name is originated from Chromium media::VideoPixelFormat enum suffix and only subset of them are supported. The actual output pixel format and color space of the texture should refer to OffscreenSharedTexture object in the paint event. * argb - The requested output texture format is 8-bit unorm RGBA, with SRGB SDR color space. * rgbaf16 - The requested output texture format is 16-bit float RGBA, with scRGB HDR color space. * nv12 - The requested output texture format is 12bpp with Y plane followed by a 2x2 interleaved UV plane, with REC709 color space. * deviceScaleFactor number (optional) Experimental - The device scale factor of the offscreen rendering output. If not set, will use 1 as default. * contextIsolation boolean (опционально) - Запускать или нет API Electron и определенный скрипт preload в отдельном JavaScript-контексте. По умолчанию true . The context that the preload script runs in will only have access to its own dedicated document and window globals, as well as its own set of JavaScript builtins ( Array , Object , JSON , etc.), which are all invisible to the loaded content. The Electron API will only be available in the preload script and not the loaded page. This option should be used when loading potentially untrusted remote content to ensure the loaded content cannot tamper with the preload script and any Electron APIs being used. This option uses the same technique used by Chrome Content Scripts . You can access this context in the dev tools by selecting the 'Electron Isolated Context' entry in the combo box at the top of the Console tab. * webviewTag boolean (optional) - Whether to enable the <webview> tag . По умолчанию false . Примечание: Cкрипт preload , настроенный для <webview> , при запуске будет иметь интеграцию NodeJS, так что Вы должны убедиться, что удаленный/непроверенный контент не сможет создавать тег <webview> с возможно вредоносным скриптом preload . You can use the will-attach-webview event on webContents to strip away the preload script and to validate or alter the <webview> 's initial settings. * additionalArguments string[] (optional) - A list of strings that will be appended to process.argv in the renderer process of this app. Useful for passing small bits of data down to renderer process preload scripts. * safeDialogs boolean (optional) - Whether to enable browser style consecutive dialog protection. По умолчанию - false . * safeDialogsMessage string (опционально) - Сообщение, которое будет отображено, когда сработает последовательная защита диалогов. Если не определено, будет использовано сообщение по умолчанию, обратите внимание, что текущее сообщение по умолчанию на английском и не переведено. * disableDialogs boolean (optional) - Whether to disable dialogs completely. Overrides safeDialogs . По умолчанию - false . * navigateOnDragDrop boolean (optional) - Whether dragging and dropping a file or link onto the page causes a navigation. По умолчанию - false . * autoplayPolicy string (опционально) - политика автовоспроизведения для применения к содержимому в окне, может быть no-user-gesture-required , user-gesture-required или document-user-activation-required . По умолчанию no-user-gesture-required . * disableHtmlFullscreenWindowResize boolean (optional) - Whether to prevent the window from resizing when entering HTML Fullscreen. Default is false . * accessibleTitle string (optional) - An alternative title string provided only to accessibility tools such as screen readers. This string is not directly visible to users. * spellcheck boolean (optional) - Whether to enable the builtin spellchecker. По умолчанию - true . * enableWebSQL boolean (optional) - Whether to enable the WebSQL api . По умолчанию - true . * v8CacheOptions string (optional) - Enforces the v8 code caching policy used by blink. Accepted values are * none - Disables code caching * code - Heuristic based code caching * bypassHeatCheck - Bypass code caching heuristics but with lazy compilation * bypassHeatCheckAndEagerCompile - Same as above except compilation is eager. Default policy is code . * enablePreferredSizeMode boolean (optional) - Whether to enable preferred size mode. The preferred size is the minimum size needed to contain the layout of the document—without requiring scrolling. Enabling this will cause the preferred-size-changed event to be emitted on the WebContents when the preferred size changes. По умолчанию - false . * transparent boolean (optional) - Whether to enable background transparency for the guest page. По умолчанию - true . Note: The guest page's text and background colors are derived from the color scheme of its root element. When transparency is enabled, the text color will still change accordingly but the background will remain transparent. * enableDeprecatedPaste boolean (optional) Deprecated - Whether to enable the paste execCommand . По умолчанию - false . * focusOnNavigation boolean (optional) - Whether to focus the WebContents when navigating. По умолчанию - true . * paintWhenInitiallyHidden boolean (опционально) - Должен ли рендерер быть активным, когда show равен false и он только что создан. Для document.visibilityState для корректной работы при первой загрузке с show: false необходимо уста

Links found on this page

  1. Перейти к основному содержанию [direct]
  2. Electron [direct]
  3. Документация [direct]
  4. API [direct]
  5. Блог [direct]
  6. Electron Forge [direct]
  7. Electron Fiddle [direct]
  8. Управление [direct]
  9. Примеры [direct]
  10. Ресурсы [direct]
  11. Релизы [direct]
  12. English [direct]
  13. Deutsch [direct]
  14. Español [direct]
  15. Français [direct]
  16. 日本語 [direct]
  17. Português [direct]
  18. 中文 [direct]
  19. autoUpdater [direct]
  20. BaseWindow [direct]
  21. BrowserView Deprecated [direct]
  22. clipboard [direct]
  23. contentTracing [direct]
  24. crashReporter [direct]
  25. desktopCapturer [direct]
  26. dialog [direct]
  27. globalShortcut [direct]
  28. ImageView [direct]
  29. inAppPurchase [direct]
  30. ipcMain [direct]
  31. Menu [direct]
  32. MenuItem [direct]
  33. MessageChannelMain [direct]
  34. MessagePortMain [direct]
  35. nativeImage [direct]
  36. nativeTheme (Родная тема) [direct]
  37. net [direct]
  38. netLog [direct]
  39. Notification (Оповещения) [direct]
  40. powerMonitor [direct]
  41. powerSaveBlocker [direct]
  42. process [direct]
  43. protocol [direct]
  44. pushNotifications [direct]
  45. safeStorage [direct]
  46. screen [direct]
  47. session [direct]
  48. sharedTexture [direct]
  49. ShareMenu [direct]
  50. shell [direct]
  51. systemPreferences [direct]
  52. TouchBar [direct]
  53. Tray [direct]
  54. utilityProcess [direct]
  55. webContents [direct]
  56. WebContentsView [direct]
  57. webFrameMain [direct]
  58. View [direct]
  59. Пользовательские DOM-элементы [direct]
  60. Chromium и Node.js [direct]
  61. Классы [direct]
  62. Структуры API [direct]
  63. Main [direct]
  64. Window Customization [direct]
  65. API видимости страниц [direct]
  66. EventEmitter [direct]
  67. the FAQ [direct]
  68. BrowserWindowConstructorOptions [direct]
  69. WebPreferences [direct]
  70. Multithreading [direct]
  71. here [direct]
  72. here [direct]
  73. RuntimeEnabledFeatures.json5 [direct]
  74. offscreen rendering tutorial [direct]
  75. media::VideoPixelFormat [direct]
  76. OffscreenSharedTexture [direct]
  77. Chrome Content Scripts [direct]
  78. WebSQL api [direct]
  79. color scheme [direct]
  80. execCommand [direct]