window-setup.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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) => {
  210. if (!process.sandboxed && !guestInstanceId) {
  211. // Override default window.close.
  212. window.close = function () {
  213. ipcRendererInternal.send(IPC_MESSAGES.BROWSER_WINDOW_CLOSE);
  214. };
  215. if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['close'], window.close);
  216. }
  217. if (!usesNativeWindowOpen) {
  218. // TODO(MarshallOfSound): Make compatible with ctx isolation without hole-punch
  219. // Make the browser window or guest view emit "new-window" event.
  220. window.open = function (url?: string, frameName?: string, features?: string) {
  221. if (url != null && url !== '') {
  222. url = resolveURL(url, location.href);
  223. }
  224. const guestId = ipcRendererInternal.sendSync(IPC_MESSAGES.GUEST_WINDOW_MANAGER_WINDOW_OPEN, url, toString(frameName), toString(features));
  225. if (guestId != null) {
  226. return getOrCreateProxy(guestId) as any as WindowProxy;
  227. } else {
  228. return null;
  229. }
  230. };
  231. if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['open'], window.open);
  232. }
  233. // If this window uses nativeWindowOpen, but its opener window does not, we
  234. // need to proxy window.opener in order to let the page communicate with its
  235. // opener.
  236. // Additionally, windows opened from a nativeWindowOpen child of a
  237. // non-nativeWindowOpen parent will initially have their WebPreferences
  238. // copied from their opener before having them updated, meaning openerId is
  239. // initially incorrect. We detect this situation by checking for
  240. // window.opener, which will be non-null for a natively-opened child, so we
  241. // can ignore the openerId in that case, since it's incorrectly copied from
  242. // the parent. This is, uh, confusing, so here's a diagram that will maybe
  243. // help?
  244. //
  245. // [ grandparent window ] --> [ parent window ] --> [ child window ]
  246. // n.W.O = false n.W.O = true n.W.O = true
  247. // id = 1 id = 2 id = 3
  248. // openerId = 0 openerId = 1 openerId = 1 <- !!wrong!!
  249. // opener = null opener = null opener = [parent window]
  250. if (openerId && !window.opener) {
  251. window.opener = getOrCreateProxy(openerId);
  252. if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['opener'], window.opener);
  253. }
  254. // But we do not support prompt().
  255. window.prompt = function () {
  256. throw new Error('prompt() is and will not be supported.');
  257. };
  258. if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['prompt'], window.prompt);
  259. if (!usesNativeWindowOpen || openerId) {
  260. ipcRendererInternal.on(IPC_MESSAGES.GUEST_WINDOW_POSTMESSAGE, function (
  261. _event, sourceId: number, message: any, sourceOrigin: string
  262. ) {
  263. // Manually dispatch event instead of using postMessage because we also need to
  264. // set event.source.
  265. //
  266. // Why any? We can't construct a MessageEvent and we can't
  267. // use `as MessageEvent` because you're not supposed to override
  268. // data, origin, and source
  269. const event: any = document.createEvent('Event');
  270. event.initEvent('message', false, false);
  271. event.data = message;
  272. event.origin = sourceOrigin;
  273. event.source = getOrCreateProxy(sourceId);
  274. window.dispatchEvent(event as MessageEvent);
  275. });
  276. }
  277. if (guestInstanceId) {
  278. // Webview `document.visibilityState` tracks window visibility (and ignores
  279. // the actual <webview> element visibility) for backwards compatibility.
  280. // See discussion in #9178.
  281. //
  282. // Note that this results in duplicate visibilitychange events (since
  283. // Chromium also fires them) and potentially incorrect visibility change.
  284. // We should reconsider this decision for Electron 2.0.
  285. let cachedVisibilityState = isHiddenPage ? 'hidden' : 'visible';
  286. // Subscribe to visibilityState changes.
  287. ipcRendererInternal.on(IPC_MESSAGES.GUEST_INSTANCE_VISIBILITY_CHANGE, function (_event, visibilityState: VisibilityState) {
  288. if (cachedVisibilityState !== visibilityState) {
  289. cachedVisibilityState = visibilityState;
  290. document.dispatchEvent(new Event('visibilitychange'));
  291. }
  292. });
  293. // Make document.hidden and document.visibilityState return the correct value.
  294. const getDocumentHidden = () => cachedVisibilityState !== 'visible';
  295. Object.defineProperty(document, 'hidden', {
  296. get: getDocumentHidden
  297. });
  298. if (contextIsolationEnabled) internalContextBridge.overrideGlobalPropertyFromIsolatedWorld(['document', 'hidden'], getDocumentHidden);
  299. const getDocumentVisibilityState = () => cachedVisibilityState;
  300. Object.defineProperty(document, 'visibilityState', {
  301. get: getDocumentVisibilityState
  302. });
  303. if (contextIsolationEnabled) internalContextBridge.overrideGlobalPropertyFromIsolatedWorld(['document', 'visibilityState'], getDocumentVisibilityState);
  304. }
  305. };