web-view-impl.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import type * as guestViewInternalModule from '@electron/internal/renderer/web-view/guest-view-internal';
  2. import { WEB_VIEW_CONSTANTS } from '@electron/internal/renderer/web-view/web-view-constants';
  3. import { syncMethods, asyncMethods, properties } from '@electron/internal/common/web-view-methods';
  4. import type { WebViewAttribute, PartitionAttribute } from '@electron/internal/renderer/web-view/web-view-attributes';
  5. import { setupWebViewAttributes } from '@electron/internal/renderer/web-view/web-view-attributes';
  6. // ID generator.
  7. let nextId = 0;
  8. const getNextId = function () {
  9. return ++nextId;
  10. };
  11. export interface WebViewImplHooks {
  12. readonly guestViewInternal: typeof guestViewInternalModule;
  13. readonly allowGuestViewElementDefinition: NodeJS.InternalWebFrame['allowGuestViewElementDefinition'];
  14. readonly setIsWebView: (iframe: HTMLIFrameElement) => void;
  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 viewInstanceId: number
  25. // on* Event handlers.
  26. public on: Record<string, any> = {}
  27. public internalElement: HTMLIFrameElement
  28. public attributes: Map<string, WebViewAttribute>;
  29. constructor (public webviewNode: HTMLElement, private hooks: WebViewImplHooks) {
  30. // Create internal iframe element.
  31. this.internalElement = this.createInternalElement();
  32. const shadowRoot = this.webviewNode.attachShadow({ mode: 'open' });
  33. const style = shadowRoot.ownerDocument.createElement('style');
  34. style.textContent = ':host { display: flex; }';
  35. shadowRoot.appendChild(style);
  36. this.attributes = setupWebViewAttributes(this);
  37. this.viewInstanceId = getNextId();
  38. shadowRoot.appendChild(this.internalElement);
  39. // Provide access to contentWindow.
  40. Object.defineProperty(this.webviewNode, 'contentWindow', {
  41. get: () => {
  42. return this.internalElement.contentWindow;
  43. },
  44. enumerable: true
  45. });
  46. }
  47. createInternalElement () {
  48. const iframeElement = document.createElement('iframe');
  49. iframeElement.style.flex = '1 1 auto';
  50. iframeElement.style.width = '100%';
  51. iframeElement.style.border = '0';
  52. // used by RendererClientBase::IsWebViewFrame
  53. this.hooks.setIsWebView(iframeElement);
  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. this.guestInstanceId = undefined;
  66. }
  67. this.beforeFirstNavigation = true;
  68. (this.attributes.get(WEB_VIEW_CONSTANTS.ATTRIBUTE_PARTITION) as PartitionAttribute).validPartitionId = true;
  69. // Since attachment swaps a local frame for a remote frame, we need our
  70. // internal iframe element to be local again before we can reattach.
  71. const newFrame = this.createInternalElement();
  72. const oldFrame = this.internalElement;
  73. this.internalElement = newFrame;
  74. if (oldFrame && oldFrame.parentNode) {
  75. oldFrame.parentNode.replaceChild(newFrame, oldFrame);
  76. }
  77. }
  78. // This observer monitors mutations to attributes of the <webview> and
  79. // updates the BrowserPlugin properties accordingly. In turn, updating
  80. // a BrowserPlugin property will update the corresponding BrowserPlugin
  81. // attribute, if necessary. See BrowserPlugin::UpdateDOMAttribute for more
  82. // details.
  83. handleWebviewAttributeMutation (attributeName: string, oldValue: any, newValue: any) {
  84. if (!this.attributes.has(attributeName) || this.attributes.get(attributeName)!.ignoreMutation) {
  85. return;
  86. }
  87. // Let the changed attribute handle its own mutation
  88. this.attributes.get(attributeName)!.handleMutation(oldValue, newValue);
  89. }
  90. onElementResize () {
  91. const props = {
  92. newWidth: this.webviewNode.clientWidth,
  93. newHeight: this.webviewNode.clientHeight
  94. };
  95. this.dispatchEvent('resize', props);
  96. }
  97. createGuest () {
  98. this.internalInstanceId = getNextId();
  99. this.hooks.guestViewInternal.createGuest(this.internalElement, this.internalInstanceId, this.buildParams())
  100. .then(guestInstanceId => {
  101. this.attachGuestInstance(guestInstanceId);
  102. });
  103. }
  104. dispatchEvent (eventName: string, props: Record<string, any> = {}) {
  105. const event = new Event(eventName);
  106. Object.assign(event, props);
  107. this.webviewNode.dispatchEvent(event);
  108. if (eventName === 'load-commit') {
  109. this.onLoadCommit(props);
  110. } else if (eventName === '-focus-change') {
  111. this.onFocusChange();
  112. }
  113. }
  114. // Adds an 'on<event>' property on the webview, which can be used to set/unset
  115. // an event handler.
  116. setupEventProperty (eventName: string) {
  117. const propertyName = `on${eventName.toLowerCase()}`;
  118. return Object.defineProperty(this.webviewNode, propertyName, {
  119. get: () => {
  120. return this.on[propertyName];
  121. },
  122. set: (value) => {
  123. if (this.on[propertyName]) {
  124. this.webviewNode.removeEventListener(eventName, this.on[propertyName]);
  125. }
  126. this.on[propertyName] = value;
  127. if (value) {
  128. return this.webviewNode.addEventListener(eventName, value);
  129. }
  130. },
  131. enumerable: true
  132. });
  133. }
  134. // Updates state upon loadcommit.
  135. onLoadCommit (props: Record<string, any>) {
  136. const oldValue = this.webviewNode.getAttribute(WEB_VIEW_CONSTANTS.ATTRIBUTE_SRC);
  137. const newValue = props.url;
  138. if (props.isMainFrame && (oldValue !== newValue)) {
  139. // Touching the src attribute triggers a navigation. To avoid
  140. // triggering a page reload on every guest-initiated navigation,
  141. // we do not handle this mutation.
  142. this.attributes.get(WEB_VIEW_CONSTANTS.ATTRIBUTE_SRC)!.setValueIgnoreMutation(newValue);
  143. }
  144. }
  145. // Emits focus/blur events.
  146. onFocusChange () {
  147. const hasFocus = this.webviewNode.ownerDocument.activeElement === this.webviewNode;
  148. if (hasFocus !== this.hasFocus) {
  149. this.hasFocus = hasFocus;
  150. this.dispatchEvent(hasFocus ? 'focus' : 'blur');
  151. }
  152. }
  153. onAttach (storagePartitionId: number) {
  154. return this.attributes.get(WEB_VIEW_CONSTANTS.ATTRIBUTE_PARTITION)!.setValue(storagePartitionId);
  155. }
  156. buildParams () {
  157. const params: Record<string, any> = {
  158. instanceId: this.viewInstanceId
  159. };
  160. for (const [attributeName, attribute] of this.attributes) {
  161. params[attributeName] = attribute.getValue();
  162. }
  163. return params;
  164. }
  165. attachGuestInstance (guestInstanceId: number) {
  166. if (guestInstanceId === -1) {
  167. // Do nothing
  168. return;
  169. }
  170. if (!this.elementAttached) {
  171. // The element could be detached before we got response from browser.
  172. // Destroy the backing webContents to avoid any zombie nodes in the frame tree.
  173. this.hooks.guestViewInternal.detachGuest(guestInstanceId);
  174. return;
  175. }
  176. this.guestInstanceId = guestInstanceId;
  177. // TODO(zcbenz): Should we deprecate the "resize" event? Wait, it is not
  178. // even documented.
  179. this.resizeObserver = new ResizeObserver(this.onElementResize.bind(this));
  180. this.resizeObserver.observe(this.internalElement);
  181. }
  182. }
  183. // I wish eslint wasn't so stupid, but it is
  184. // eslint-disable-next-line
  185. export const setupMethods = (WebViewElement: typeof ElectronInternal.WebViewElement, hooks: WebViewImplHooks) => {
  186. // Focusing the webview should move page focus to the underlying iframe.
  187. WebViewElement.prototype.focus = function () {
  188. this.contentWindow.focus();
  189. };
  190. // Forward proto.foo* method calls to WebViewImpl.foo*.
  191. for (const method of syncMethods) {
  192. (WebViewElement.prototype as Record<string, any>)[method] = function (this: ElectronInternal.WebViewElement, ...args: Array<any>) {
  193. return hooks.guestViewInternal.invokeSync(this.getWebContentsId(), method, args);
  194. };
  195. }
  196. for (const method of asyncMethods) {
  197. (WebViewElement.prototype as Record<string, any>)[method] = function (this: ElectronInternal.WebViewElement, ...args: Array<any>) {
  198. return hooks.guestViewInternal.invoke(this.getWebContentsId(), method, args);
  199. };
  200. }
  201. const createPropertyGetter = function (property: string) {
  202. return function (this: ElectronInternal.WebViewElement) {
  203. return hooks.guestViewInternal.propertyGet(this.getWebContentsId(), property);
  204. };
  205. };
  206. const createPropertySetter = function (property: string) {
  207. return function (this: ElectronInternal.WebViewElement, arg: any) {
  208. return hooks.guestViewInternal.propertySet(this.getWebContentsId(), property, arg);
  209. };
  210. };
  211. for (const property of properties) {
  212. Object.defineProperty(WebViewElement.prototype, property, {
  213. get: createPropertyGetter(property),
  214. set: createPropertySetter(property)
  215. });
  216. }
  217. };