web-view-impl.ts 9.3 KB

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