window-setup.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal';
  2. import * as ipcRendererUtils from '@electron/internal/renderer/ipc-renderer-internal-utils';
  3. import { internalContextBridge } from '@electron/internal/renderer/api/context-bridge';
  4. const { contextIsolationEnabled, isInIsolatedWorld } = internalContextBridge;
  5. const shouldUseContextBridge = contextIsolationEnabled && isInIsolatedWorld();
  6. // This file implements the following APIs over the ctx bridge:
  7. // - window.open()
  8. // - window.opener.blur()
  9. // - window.opener.close()
  10. // - window.opener.eval()
  11. // - window.opener.focus()
  12. // - window.opener.location
  13. // - window.opener.print()
  14. // - window.opener.closed
  15. // - window.opener.postMessage()
  16. // - window.history.back()
  17. // - window.history.forward()
  18. // - window.history.go()
  19. // - window.history.length
  20. // - window.prompt()
  21. // - document.hidden
  22. // - document.visibilityState
  23. // Helper function to resolve relative url.
  24. const resolveURL = (url: string, base: string) => new URL(url, base).href;
  25. // Use this method to ensure values expected as strings in the main process
  26. // are convertible to strings in the renderer process. This ensures exceptions
  27. // converting values to strings are thrown in this process.
  28. const toString = (value: any) => {
  29. return value != null ? `${value}` : value;
  30. };
  31. const windowProxies: Record<number, BrowserWindowProxy> = {};
  32. const getOrCreateProxy = (guestId: number): SafelyBoundBrowserWindowProxy => {
  33. let proxy = windowProxies[guestId];
  34. if (proxy == null) {
  35. proxy = new BrowserWindowProxy(guestId);
  36. windowProxies[guestId] = proxy;
  37. }
  38. return proxy.getSafe();
  39. };
  40. const removeProxy = (guestId: number) => {
  41. delete windowProxies[guestId];
  42. };
  43. type LocationProperties = 'hash' | 'href' | 'host' | 'hostname' | 'origin' | 'pathname' | 'port' | 'protocol' | 'search'
  44. class LocationProxy {
  45. @LocationProxy.ProxyProperty public hash!: string;
  46. @LocationProxy.ProxyProperty public href!: string;
  47. @LocationProxy.ProxyProperty public host!: string;
  48. @LocationProxy.ProxyProperty public hostname!: string;
  49. @LocationProxy.ProxyProperty public origin!: string;
  50. @LocationProxy.ProxyProperty public pathname!: string;
  51. @LocationProxy.ProxyProperty public port!: string;
  52. @LocationProxy.ProxyProperty public protocol!: string;
  53. @LocationProxy.ProxyProperty public search!: URLSearchParams;
  54. private guestId: number;
  55. /**
  56. * Beware: This decorator will have the _prototype_ as the `target`. It defines properties
  57. * commonly found in URL on the LocationProxy.
  58. */
  59. private static ProxyProperty<T> (target: LocationProxy, propertyKey: LocationProperties) {
  60. Object.defineProperty(target, propertyKey, {
  61. enumerable: true,
  62. configurable: true,
  63. get: function (this: LocationProxy): T | string {
  64. const guestURL = this.getGuestURL();
  65. const value = guestURL ? guestURL[propertyKey] : '';
  66. return value === undefined ? '' : value;
  67. },
  68. set: function (this: LocationProxy, newVal: T) {
  69. const guestURL = this.getGuestURL();
  70. if (guestURL) {
  71. // TypeScript doesn't want us to assign to read-only variables.
  72. // It's right, that's bad, but we're doing it anway.
  73. (guestURL as any)[propertyKey] = newVal;
  74. return this._invokeWebContentsMethod('loadURL', guestURL.toString());
  75. }
  76. }
  77. });
  78. }
  79. public getSafe = () => {
  80. const that = this;
  81. return {
  82. get href () { return that.href; },
  83. set href (newValue) { that.href = newValue; },
  84. get hash () { return that.hash; },
  85. set hash (newValue) { that.hash = newValue; },
  86. get host () { return that.host; },
  87. set host (newValue) { that.host = newValue; },
  88. get hostname () { return that.hostname; },
  89. set hostname (newValue) { that.hostname = newValue; },
  90. get origin () { return that.origin; },
  91. set origin (newValue) { that.origin = newValue; },
  92. get pathname () { return that.pathname; },
  93. set pathname (newValue) { that.pathname = newValue; },
  94. get port () { return that.port; },
  95. set port (newValue) { that.port = newValue; },
  96. get protocol () { return that.protocol; },
  97. set protocol (newValue) { that.protocol = newValue; },
  98. get search () { return that.search; },
  99. set search (newValue) { that.search = newValue; }
  100. };
  101. }
  102. constructor (guestId: number) {
  103. // eslint will consider the constructor "useless"
  104. // unless we assign them in the body. It's fine, that's what
  105. // TS would do anyway.
  106. this.guestId = guestId;
  107. this.getGuestURL = this.getGuestURL.bind(this);
  108. }
  109. public toString (): string {
  110. return this.href;
  111. }
  112. private getGuestURL (): URL | null {
  113. const urlString = this._invokeWebContentsMethodSync('getURL') as string;
  114. try {
  115. return new URL(urlString);
  116. } catch (e) {
  117. console.error('LocationProxy: failed to parse string', urlString, e);
  118. }
  119. return null;
  120. }
  121. private _invokeWebContentsMethod (method: string, ...args: any[]) {
  122. return ipcRendererUtils.invoke('ELECTRON_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', this.guestId, method, ...args);
  123. }
  124. private _invokeWebContentsMethodSync (method: string, ...args: any[]) {
  125. return ipcRendererUtils.invokeSync('ELECTRON_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', this.guestId, method, ...args);
  126. }
  127. }
  128. interface SafelyBoundBrowserWindowProxy {
  129. location: WindowProxy['location'];
  130. blur: WindowProxy['blur'];
  131. close: WindowProxy['close'];
  132. eval: typeof eval; // eslint-disable-line no-eval
  133. focus: WindowProxy['focus'];
  134. print: WindowProxy['print'];
  135. postMessage: WindowProxy['postMessage'];
  136. closed: boolean;
  137. }
  138. class BrowserWindowProxy {
  139. public closed: boolean = false
  140. private _location: LocationProxy
  141. private guestId: number
  142. // TypeScript doesn't allow getters/accessors with different types,
  143. // so for now, we'll have to make do with an "any" in the mix.
  144. // https://github.com/Microsoft/TypeScript/issues/2521
  145. public get location (): LocationProxy | any {
  146. return this._location.getSafe();
  147. }
  148. public set location (url: string | any) {
  149. url = resolveURL(url, this.location.href);
  150. this._invokeWebContentsMethod('loadURL', url);
  151. }
  152. constructor (guestId: number) {
  153. this.guestId = guestId;
  154. this._location = new LocationProxy(guestId);
  155. ipcRendererInternal.once(`ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_${guestId}`, () => {
  156. removeProxy(guestId);
  157. this.closed = true;
  158. });
  159. }
  160. public getSafe = (): SafelyBoundBrowserWindowProxy => {
  161. const that = this;
  162. return {
  163. postMessage: this.postMessage,
  164. blur: this.blur,
  165. close: this.close,
  166. focus: this.focus,
  167. print: this.print,
  168. eval: this.eval,
  169. get location () {
  170. return that.location;
  171. },
  172. set location (url: string | any) {
  173. that.location = url;
  174. },
  175. get closed () {
  176. return that.closed;
  177. }
  178. };
  179. }
  180. public close = () => {
  181. this._invokeWindowMethod('destroy');
  182. }
  183. public focus = () => {
  184. this._invokeWindowMethod('focus');
  185. }
  186. public blur = () => {
  187. this._invokeWindowMethod('blur');
  188. }
  189. public print = () => {
  190. this._invokeWebContentsMethod('print');
  191. }
  192. public postMessage = (message: any, targetOrigin: string) => {
  193. ipcRendererUtils.invoke('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', this.guestId, message, toString(targetOrigin), window.location.origin);
  194. }
  195. public eval = (code: string) => {
  196. this._invokeWebContentsMethod('executeJavaScript', code);
  197. }
  198. private _invokeWindowMethod (method: string, ...args: any[]) {
  199. return ipcRendererUtils.invoke('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, method, ...args);
  200. }
  201. private _invokeWebContentsMethod (method: string, ...args: any[]) {
  202. return ipcRendererUtils.invoke('ELECTRON_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', this.guestId, method, ...args);
  203. }
  204. }
  205. export const windowSetup = (
  206. guestInstanceId: number, openerId: number, isHiddenPage: boolean, usesNativeWindowOpen: boolean
  207. ) => {
  208. if (!process.sandboxed && guestInstanceId == null) {
  209. // Override default window.close.
  210. window.close = function () {
  211. ipcRendererInternal.sendSync('ELECTRON_BROWSER_WINDOW_CLOSE');
  212. };
  213. if (shouldUseContextBridge) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['close'], window.close);
  214. }
  215. if (!usesNativeWindowOpen) {
  216. // TODO(MarshallOfSound): Make compatible with ctx isolation without hole-punch
  217. // Make the browser window or guest view emit "new-window" event.
  218. (window as any).open = function (url?: string, frameName?: string, features?: string) {
  219. if (url != null && url !== '') {
  220. url = resolveURL(url, location.href);
  221. }
  222. const guestId = ipcRendererInternal.sendSync('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, toString(frameName), toString(features));
  223. if (guestId != null) {
  224. return getOrCreateProxy(guestId);
  225. } else {
  226. return null;
  227. }
  228. };
  229. if (shouldUseContextBridge) internalContextBridge.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['open'], window.open);
  230. }
  231. if (openerId != null) {
  232. window.opener = getOrCreateProxy(openerId);
  233. if (shouldUseContextBridge) internalContextBridge.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['opener'], window.opener);
  234. }
  235. // But we do not support prompt().
  236. window.prompt = function () {
  237. throw new Error('prompt() is and will not be supported.');
  238. };
  239. if (shouldUseContextBridge) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['prompt'], window.prompt);
  240. if (!usesNativeWindowOpen || openerId != null) {
  241. ipcRendererInternal.on('ELECTRON_GUEST_WINDOW_POSTMESSAGE', function (
  242. _event, sourceId: number, message: any, sourceOrigin: string
  243. ) {
  244. // Manually dispatch event instead of using postMessage because we also need to
  245. // set event.source.
  246. //
  247. // Why any? We can't construct a MessageEvent and we can't
  248. // use `as MessageEvent` because you're not supposed to override
  249. // data, origin, and source
  250. const event: any = document.createEvent('Event');
  251. event.initEvent('message', false, false);
  252. event.data = message;
  253. event.origin = sourceOrigin;
  254. event.source = getOrCreateProxy(sourceId);
  255. window.dispatchEvent(event as MessageEvent);
  256. });
  257. }
  258. if (!process.sandboxed) {
  259. window.history.back = function () {
  260. ipcRendererInternal.send('ELECTRON_NAVIGATION_CONTROLLER_GO_BACK');
  261. };
  262. if (shouldUseContextBridge) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['history', 'back'], window.history.back);
  263. window.history.forward = function () {
  264. ipcRendererInternal.send('ELECTRON_NAVIGATION_CONTROLLER_GO_FORWARD');
  265. };
  266. if (shouldUseContextBridge) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['history', 'forward'], window.history.forward);
  267. window.history.go = function (offset: number) {
  268. ipcRendererInternal.send('ELECTRON_NAVIGATION_CONTROLLER_GO_TO_OFFSET', +offset);
  269. };
  270. if (shouldUseContextBridge) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['history', 'go'], window.history.go);
  271. const getHistoryLength = () => ipcRendererInternal.sendSync('ELECTRON_NAVIGATION_CONTROLLER_LENGTH');
  272. Object.defineProperty(window.history, 'length', {
  273. get: getHistoryLength,
  274. set () {}
  275. });
  276. // TODO(MarshallOfSound): Fix so that the internal context bridge can override a non-configurable property
  277. // if (shouldUseContextBridge) internalContextBridge.overrideGlobalPropertyFromIsolatedWorld(['history', 'length'], getHistoryLength);
  278. }
  279. if (guestInstanceId != null) {
  280. // Webview `document.visibilityState` tracks window visibility (and ignores
  281. // the actual <webview> element visibility) for backwards compatibility.
  282. // See discussion in #9178.
  283. //
  284. // Note that this results in duplicate visibilitychange events (since
  285. // Chromium also fires them) and potentially incorrect visibility change.
  286. // We should reconsider this decision for Electron 2.0.
  287. let cachedVisibilityState = isHiddenPage ? 'hidden' : 'visible';
  288. // Subscribe to visibilityState changes.
  289. ipcRendererInternal.on('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', function (_event, visibilityState: VisibilityState) {
  290. if (cachedVisibilityState !== visibilityState) {
  291. cachedVisibilityState = visibilityState;
  292. document.dispatchEvent(new Event('visibilitychange'));
  293. }
  294. });
  295. // Make document.hidden and document.visibilityState return the correct value.
  296. const getDocumentHidden = () => cachedVisibilityState !== 'visible';
  297. Object.defineProperty(document, 'hidden', {
  298. get: getDocumentHidden
  299. });
  300. if (shouldUseContextBridge) internalContextBridge.overrideGlobalPropertyFromIsolatedWorld(['document', 'hidden'], getDocumentHidden);
  301. const getDocumentVisibilityState = () => cachedVisibilityState;
  302. Object.defineProperty(document, 'visibilityState', {
  303. get: getDocumentVisibilityState
  304. });
  305. if (shouldUseContextBridge) internalContextBridge.overrideGlobalPropertyFromIsolatedWorld(['document', 'visibilityState'], getDocumentVisibilityState);
  306. }
  307. };