window-setup.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
  5. const { contextIsolationEnabled } = internalContextBridge;
  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 = new Map<number, BrowserWindowProxy>();
  32. const getOrCreateProxy = (guestId: number): SafelyBoundBrowserWindowProxy => {
  33. let proxy = windowProxies.get(guestId);
  34. if (proxy == null) {
  35. proxy = new BrowserWindowProxy(guestId);
  36. windowProxies.set(guestId, proxy);
  37. }
  38. return proxy.getSafe();
  39. };
  40. const removeProxy = (guestId: number) => {
  41. windowProxies.delete(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 anyway.
  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 maybeURL = this._invokeWebContentsMethodSync('getURL') as string;
  114. // When there's no previous frame the url will be blank, so account for that here
  115. // to prevent url parsing errors on an empty string.
  116. const urlString = maybeURL !== '' ? maybeURL : 'about:blank';
  117. try {
  118. return new URL(urlString);
  119. } catch (e) {
  120. console.error('LocationProxy: failed to parse string', urlString, e);
  121. }
  122. return null;
  123. }
  124. private _invokeWebContentsMethod (method: string, ...args: any[]) {
  125. return ipcRendererInternal.invoke(IPC_MESSAGES.GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD, this.guestId, method, ...args);
  126. }
  127. private _invokeWebContentsMethodSync (method: string, ...args: any[]) {
  128. return ipcRendererUtils.invokeSync(IPC_MESSAGES.GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD, this.guestId, method, ...args);
  129. }
  130. }
  131. interface SafelyBoundBrowserWindowProxy {
  132. location: WindowProxy['location'];
  133. blur: WindowProxy['blur'];
  134. close: WindowProxy['close'];
  135. eval: typeof eval; // eslint-disable-line no-eval
  136. focus: WindowProxy['focus'];
  137. print: WindowProxy['print'];
  138. postMessage: WindowProxy['postMessage'];
  139. closed: boolean;
  140. }
  141. class BrowserWindowProxy {
  142. public closed: boolean = false
  143. private _location: LocationProxy
  144. private guestId: number
  145. // TypeScript doesn't allow getters/accessors with different types,
  146. // so for now, we'll have to make do with an "any" in the mix.
  147. // https://github.com/Microsoft/TypeScript/issues/2521
  148. public get location (): LocationProxy | any {
  149. return this._location.getSafe();
  150. }
  151. public set location (url: string | any) {
  152. url = resolveURL(url, this.location.href);
  153. this._invokeWebContentsMethod('loadURL', url);
  154. }
  155. constructor (guestId: number) {
  156. this.guestId = guestId;
  157. this._location = new LocationProxy(guestId);
  158. ipcRendererInternal.once(`${IPC_MESSAGES.GUEST_WINDOW_MANAGER_WINDOW_CLOSED}_${guestId}`, () => {
  159. removeProxy(guestId);
  160. this.closed = true;
  161. });
  162. }
  163. public getSafe = (): SafelyBoundBrowserWindowProxy => {
  164. const that = this;
  165. return {
  166. postMessage: this.postMessage,
  167. blur: this.blur,
  168. close: this.close,
  169. focus: this.focus,
  170. print: this.print,
  171. eval: this.eval,
  172. get location () {
  173. return that.location;
  174. },
  175. set location (url: string | any) {
  176. that.location = url;
  177. },
  178. get closed () {
  179. return that.closed;
  180. }
  181. };
  182. }
  183. public close = () => {
  184. this._invokeWindowMethod('destroy');
  185. }
  186. public focus = () => {
  187. this._invokeWindowMethod('focus');
  188. }
  189. public blur = () => {
  190. this._invokeWindowMethod('blur');
  191. }
  192. public print = () => {
  193. this._invokeWebContentsMethod('print');
  194. }
  195. public postMessage = (message: any, targetOrigin: string) => {
  196. ipcRendererInternal.invoke(IPC_MESSAGES.GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE, this.guestId, message, toString(targetOrigin), window.location.origin);
  197. }
  198. public eval = (code: string) => {
  199. this._invokeWebContentsMethod('executeJavaScript', code);
  200. }
  201. private _invokeWindowMethod (method: string, ...args: any[]) {
  202. return ipcRendererInternal.invoke(IPC_MESSAGES.GUEST_WINDOW_MANAGER_WINDOW_METHOD, this.guestId, method, ...args);
  203. }
  204. private _invokeWebContentsMethod (method: string, ...args: any[]) {
  205. return ipcRendererInternal.invoke(IPC_MESSAGES.GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD, this.guestId, method, ...args);
  206. }
  207. }
  208. export const windowSetup = (
  209. guestInstanceId: number, openerId: number, isHiddenPage: boolean, usesNativeWindowOpen: boolean, rendererProcessReuseEnabled: boolean
  210. ) => {
  211. if (!process.sandboxed && guestInstanceId == null) {
  212. // Override default window.close.
  213. window.close = function () {
  214. ipcRendererInternal.send(IPC_MESSAGES.BROWSER_WINDOW_CLOSE);
  215. };
  216. if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['close'], window.close);
  217. }
  218. if (!usesNativeWindowOpen) {
  219. // TODO(MarshallOfSound): Make compatible with ctx isolation without hole-punch
  220. // Make the browser window or guest view emit "new-window" event.
  221. window.open = function (url?: string, frameName?: string, features?: string) {
  222. if (url != null && url !== '') {
  223. url = resolveURL(url, location.href);
  224. }
  225. const guestId = ipcRendererInternal.sendSync(IPC_MESSAGES.GUEST_WINDOW_MANAGER_WINDOW_OPEN, url, toString(frameName), toString(features));
  226. if (guestId != null) {
  227. return getOrCreateProxy(guestId) as any as WindowProxy;
  228. } else {
  229. return null;
  230. }
  231. };
  232. if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['open'], window.open);
  233. }
  234. if (openerId != null) {
  235. window.opener = getOrCreateProxy(openerId);
  236. if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['opener'], window.opener);
  237. }
  238. // But we do not support prompt().
  239. window.prompt = function () {
  240. throw new Error('prompt() is and will not be supported.');
  241. };
  242. if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['prompt'], window.prompt);
  243. if (!usesNativeWindowOpen || openerId != null) {
  244. ipcRendererInternal.on(IPC_MESSAGES.GUEST_WINDOW_POSTMESSAGE, function (
  245. _event, sourceId: number, message: any, sourceOrigin: string
  246. ) {
  247. // Manually dispatch event instead of using postMessage because we also need to
  248. // set event.source.
  249. //
  250. // Why any? We can't construct a MessageEvent and we can't
  251. // use `as MessageEvent` because you're not supposed to override
  252. // data, origin, and source
  253. const event: any = document.createEvent('Event');
  254. event.initEvent('message', false, false);
  255. event.data = message;
  256. event.origin = sourceOrigin;
  257. event.source = getOrCreateProxy(sourceId);
  258. window.dispatchEvent(event as MessageEvent);
  259. });
  260. }
  261. if (!process.sandboxed && !rendererProcessReuseEnabled) {
  262. window.history.back = function () {
  263. ipcRendererInternal.send(IPC_MESSAGES.NAVIGATION_CONTROLLER_GO_BACK);
  264. };
  265. if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['history', 'back'], window.history.back);
  266. window.history.forward = function () {
  267. ipcRendererInternal.send(IPC_MESSAGES.NAVIGATION_CONTROLLER_GO_FORWARD);
  268. };
  269. if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['history', 'forward'], window.history.forward);
  270. window.history.go = function (offset: number) {
  271. ipcRendererInternal.send(IPC_MESSAGES.NAVIGATION_CONTROLLER_GO_TO_OFFSET, +offset);
  272. };
  273. if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['history', 'go'], window.history.go);
  274. const getHistoryLength = () => ipcRendererInternal.sendSync(IPC_MESSAGES.NAVIGATION_CONTROLLER_LENGTH);
  275. Object.defineProperty(window.history, 'length', {
  276. get: getHistoryLength,
  277. set () {}
  278. });
  279. if (contextIsolationEnabled) internalContextBridge.overrideGlobalPropertyFromIsolatedWorld(['history', 'length'], getHistoryLength);
  280. }
  281. if (guestInstanceId != null) {
  282. // Webview `document.visibilityState` tracks window visibility (and ignores
  283. // the actual <webview> element visibility) for backwards compatibility.
  284. // See discussion in #9178.
  285. //
  286. // Note that this results in duplicate visibilitychange events (since
  287. // Chromium also fires them) and potentially incorrect visibility change.
  288. // We should reconsider this decision for Electron 2.0.
  289. let cachedVisibilityState = isHiddenPage ? 'hidden' : 'visible';
  290. // Subscribe to visibilityState changes.
  291. ipcRendererInternal.on(IPC_MESSAGES.GUEST_INSTANCE_VISIBILITY_CHANGE, function (_event, visibilityState: VisibilityState) {
  292. if (cachedVisibilityState !== visibilityState) {
  293. cachedVisibilityState = visibilityState;
  294. document.dispatchEvent(new Event('visibilitychange'));
  295. }
  296. });
  297. // Make document.hidden and document.visibilityState return the correct value.
  298. const getDocumentHidden = () => cachedVisibilityState !== 'visible';
  299. Object.defineProperty(document, 'hidden', {
  300. get: getDocumentHidden
  301. });
  302. if (contextIsolationEnabled) internalContextBridge.overrideGlobalPropertyFromIsolatedWorld(['document', 'hidden'], getDocumentHidden);
  303. const getDocumentVisibilityState = () => cachedVisibilityState;
  304. Object.defineProperty(document, 'visibilityState', {
  305. get: getDocumentVisibilityState
  306. });
  307. if (contextIsolationEnabled) internalContextBridge.overrideGlobalPropertyFromIsolatedWorld(['document', 'visibilityState'], getDocumentVisibilityState);
  308. }
  309. };