window-setup.ts 13 KB

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