web-view-impl.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import { deprecate, remote, webFrame } from 'electron'
  2. import * as ipcRendererUtils from '@electron/internal/renderer/ipc-renderer-internal-utils'
  3. import * as guestViewInternal from '@electron/internal/renderer/web-view/guest-view-internal'
  4. import { WEB_VIEW_CONSTANTS } from '@electron/internal/renderer/web-view/web-view-constants'
  5. import {
  6. syncMethods,
  7. asyncCallbackMethods,
  8. asyncPromiseMethods
  9. } from '@electron/internal/common/web-view-methods'
  10. const v8Util = process.electronBinding('v8_util')
  11. // ID generator.
  12. let nextId = 0
  13. const getNextId = function () {
  14. return ++nextId
  15. }
  16. // Represents the internal state of the WebView node.
  17. export class WebViewImpl {
  18. public beforeFirstNavigation = true
  19. public elementAttached = false
  20. public guestInstanceId?: number
  21. public hasFocus = false
  22. public internalInstanceId?: number;
  23. public resizeObserver?: ResizeObserver;
  24. public userAgentOverride?: string;
  25. public viewInstanceId: number
  26. // on* Event handlers.
  27. public on: Record<string, any> = {}
  28. public internalElement: HTMLIFrameElement
  29. // Replaced in web-view-attributes
  30. public attributes: Record<string, any> = {}
  31. public setupWebViewAttributes (): void {}
  32. constructor (public webviewNode: HTMLElement) {
  33. // Create internal iframe element.
  34. this.internalElement = this.createInternalElement()
  35. const shadowRoot = this.webviewNode.attachShadow({ mode: 'open' })
  36. shadowRoot.innerHTML = '<!DOCTYPE html><style type="text/css">:host { display: flex; }</style>'
  37. this.setupWebViewAttributes()
  38. this.viewInstanceId = getNextId()
  39. shadowRoot.appendChild(this.internalElement)
  40. // Provide access to contentWindow.
  41. Object.defineProperty(this.webviewNode, 'contentWindow', {
  42. get: () => {
  43. return this.internalElement.contentWindow
  44. },
  45. enumerable: true
  46. })
  47. }
  48. createInternalElement () {
  49. const iframeElement = document.createElement('iframe')
  50. iframeElement.style.flex = '1 1 auto'
  51. iframeElement.style.width = '100%'
  52. iframeElement.style.border = '0'
  53. v8Util.setHiddenValue(iframeElement, 'internal', this)
  54. return iframeElement
  55. }
  56. // Resets some state upon reattaching <webview> element to the DOM.
  57. reset () {
  58. // If guestInstanceId is defined then the <webview> has navigated and has
  59. // already picked up a partition ID. Thus, we need to reset the initialization
  60. // state. However, it may be the case that beforeFirstNavigation is false BUT
  61. // guestInstanceId has yet to be initialized. This means that we have not
  62. // heard back from createGuest yet. We will not reset the flag in this case so
  63. // that we don't end up allocating a second guest.
  64. if (this.guestInstanceId) {
  65. guestViewInternal.destroyGuest(this.guestInstanceId)
  66. this.guestInstanceId = void 0
  67. }
  68. this.beforeFirstNavigation = true
  69. this.attributes[WEB_VIEW_CONSTANTS.ATTRIBUTE_PARTITION].validPartitionId = true
  70. // Since attachment swaps a local frame for a remote frame, we need our
  71. // internal iframe element to be local again before we can reattach.
  72. const newFrame = this.createInternalElement()
  73. const oldFrame = this.internalElement
  74. this.internalElement = newFrame
  75. if (oldFrame && oldFrame.parentNode) {
  76. oldFrame.parentNode.replaceChild(newFrame, oldFrame)
  77. }
  78. }
  79. // This observer monitors mutations to attributes of the <webview> and
  80. // updates the BrowserPlugin properties accordingly. In turn, updating
  81. // a BrowserPlugin property will update the corresponding BrowserPlugin
  82. // attribute, if necessary. See BrowserPlugin::UpdateDOMAttribute for more
  83. // details.
  84. handleWebviewAttributeMutation (attributeName: string, oldValue: any, newValue: any) {
  85. if (!this.attributes[attributeName] || this.attributes[attributeName].ignoreMutation) {
  86. return
  87. }
  88. // Let the changed attribute handle its own mutation
  89. this.attributes[attributeName].handleMutation(oldValue, newValue)
  90. }
  91. onElementResize () {
  92. const resizeEvent = new Event('resize') as ElectronInternal.WebFrameResizeEvent
  93. resizeEvent.newWidth = this.webviewNode.clientWidth
  94. resizeEvent.newHeight = this.webviewNode.clientHeight
  95. this.dispatchEvent(resizeEvent)
  96. }
  97. createGuest () {
  98. guestViewInternal.createGuest(this.buildParams()).then(guestInstanceId => {
  99. this.attachGuestInstance(guestInstanceId)
  100. })
  101. }
  102. createGuestSync () {
  103. this.beforeFirstNavigation = false
  104. this.attachGuestInstance(guestViewInternal.createGuestSync(this.buildParams()))
  105. }
  106. dispatchEvent (webViewEvent: Electron.Event) {
  107. this.webviewNode.dispatchEvent(webViewEvent)
  108. }
  109. // Adds an 'on<event>' property on the webview, which can be used to set/unset
  110. // an event handler.
  111. setupEventProperty (eventName: string) {
  112. const propertyName = `on${eventName.toLowerCase()}`
  113. return Object.defineProperty(this.webviewNode, propertyName, {
  114. get: () => {
  115. return this.on[propertyName]
  116. },
  117. set: (value) => {
  118. if (this.on[propertyName]) {
  119. this.webviewNode.removeEventListener(eventName, this.on[propertyName])
  120. }
  121. this.on[propertyName] = value
  122. if (value) {
  123. return this.webviewNode.addEventListener(eventName, value)
  124. }
  125. },
  126. enumerable: true
  127. })
  128. }
  129. // Updates state upon loadcommit.
  130. onLoadCommit (webViewEvent: ElectronInternal.WebViewEvent) {
  131. const oldValue = this.webviewNode.getAttribute(WEB_VIEW_CONSTANTS.ATTRIBUTE_SRC)
  132. const newValue = webViewEvent.url
  133. if (webViewEvent.isMainFrame && (oldValue !== newValue)) {
  134. // Touching the src attribute triggers a navigation. To avoid
  135. // triggering a page reload on every guest-initiated navigation,
  136. // we do not handle this mutation.
  137. this.attributes[WEB_VIEW_CONSTANTS.ATTRIBUTE_SRC].setValueIgnoreMutation(newValue)
  138. }
  139. }
  140. // Emits focus/blur events.
  141. onFocusChange () {
  142. const hasFocus = document.activeElement === this.webviewNode
  143. if (hasFocus !== this.hasFocus) {
  144. this.hasFocus = hasFocus
  145. this.dispatchEvent(new Event(hasFocus ? 'focus' : 'blur'))
  146. }
  147. }
  148. onAttach (storagePartitionId: number) {
  149. return this.attributes[WEB_VIEW_CONSTANTS.ATTRIBUTE_PARTITION].setValue(storagePartitionId)
  150. }
  151. buildParams () {
  152. const params: Record<string, any> = {
  153. instanceId: this.viewInstanceId,
  154. userAgentOverride: this.userAgentOverride
  155. }
  156. for (const attributeName in this.attributes) {
  157. if (this.attributes.hasOwnProperty(attributeName)) {
  158. params[attributeName] = this.attributes[attributeName].getValue()
  159. }
  160. }
  161. return params
  162. }
  163. attachGuestInstance (guestInstanceId: number) {
  164. if (!this.elementAttached) {
  165. // The element could be detached before we got response from browser.
  166. return
  167. }
  168. this.internalInstanceId = getNextId()
  169. this.guestInstanceId = guestInstanceId
  170. guestViewInternal.attachGuest(
  171. this.internalInstanceId,
  172. this.guestInstanceId,
  173. this.buildParams(),
  174. this.internalElement.contentWindow!
  175. )
  176. // ResizeObserver is a browser global not recognized by "standard".
  177. /* globals ResizeObserver */
  178. // TODO(zcbenz): Should we deprecate the "resize" event? Wait, it is not
  179. // even documented.
  180. this.resizeObserver = new ResizeObserver(this.onElementResize.bind(this))
  181. this.resizeObserver.observe(this.internalElement)
  182. }
  183. }
  184. export const setupAttributes = () => {
  185. require('@electron/internal/renderer/web-view/web-view-attributes')
  186. }
  187. // I wish eslint wasn't so stupid, but it is
  188. // eslint-disable-next-line
  189. export const setupMethods = (WebViewElement: typeof ElectronInternal.WebViewElement) => {
  190. WebViewElement.prototype.getWebContentsId = function () {
  191. const internal = v8Util.getHiddenValue<WebViewImpl>(this, 'internal')
  192. if (!internal.guestInstanceId) {
  193. throw new Error('The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.')
  194. }
  195. return internal.guestInstanceId
  196. }
  197. // WebContents associated with this webview.
  198. WebViewElement.prototype.getWebContents = function () {
  199. if (!remote) {
  200. throw new Error('getGuestWebContents requires remote, which is not enabled')
  201. }
  202. const internal = v8Util.getHiddenValue<WebViewImpl>(this, 'internal')
  203. if (!internal.guestInstanceId) {
  204. internal.createGuestSync()
  205. }
  206. return (remote as Electron.RemoteInternal).getGuestWebContents(internal.guestInstanceId!)
  207. }
  208. // Focusing the webview should move page focus to the underlying iframe.
  209. WebViewElement.prototype.focus = function () {
  210. this.contentWindow.focus()
  211. }
  212. // Forward proto.foo* method calls to WebViewImpl.foo*.
  213. const createBlockHandler = function (method: string) {
  214. return function (this: ElectronInternal.WebViewElement, ...args: Array<any>) {
  215. return ipcRendererUtils.invokeSync('ELECTRON_GUEST_VIEW_MANAGER_CALL', this.getWebContentsId(), method, args)
  216. }
  217. }
  218. for (const method of syncMethods) {
  219. (WebViewElement.prototype as Record<string, any>)[method] = createBlockHandler(method)
  220. }
  221. const createNonBlockHandler = function (method: string) {
  222. return function (this: ElectronInternal.WebViewElement, ...args: Array<any>) {
  223. ipcRendererUtils.invoke('ELECTRON_GUEST_VIEW_MANAGER_CALL', this.getWebContentsId(), method, args)
  224. }
  225. }
  226. for (const method of asyncCallbackMethods) {
  227. (WebViewElement.prototype as Record<string, any>)[method] = createNonBlockHandler(method)
  228. }
  229. const createPromiseHandler = function (method: string) {
  230. return function (this: ElectronInternal.WebViewElement, ...args: Array<any>) {
  231. return ipcRendererUtils.invoke('ELECTRON_GUEST_VIEW_MANAGER_CALL', this.getWebContentsId(), method, args)
  232. }
  233. }
  234. for (const method of asyncPromiseMethods) {
  235. (WebViewElement.prototype as Record<string, any>)[method] = deprecate.promisify(createPromiseHandler(method))
  236. }
  237. }
  238. export const webViewImplModule = {
  239. setupAttributes,
  240. setupMethods,
  241. guestViewInternal,
  242. webFrame,
  243. WebViewImpl
  244. }