guest-view-manager.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. 'use strict'
  2. const { webContents } = require('electron')
  3. const ipcMain = require('@electron/internal/browser/ipc-main-internal')
  4. const parseFeaturesString = require('@electron/internal/common/parse-features-string')
  5. const errorUtils = require('@electron/internal/common/error-utils')
  6. const {
  7. syncMethods,
  8. asyncCallbackMethods,
  9. asyncPromiseMethods
  10. } = require('@electron/internal/common/web-view-methods')
  11. // Doesn't exist in early initialization.
  12. let webViewManager = null
  13. const supportedWebViewEvents = [
  14. 'load-commit',
  15. 'did-attach',
  16. 'did-finish-load',
  17. 'did-fail-load',
  18. 'did-frame-finish-load',
  19. 'did-start-loading',
  20. 'did-stop-loading',
  21. 'dom-ready',
  22. 'console-message',
  23. 'context-menu',
  24. 'devtools-opened',
  25. 'devtools-closed',
  26. 'devtools-focused',
  27. 'new-window',
  28. 'will-navigate',
  29. 'did-start-navigation',
  30. 'did-navigate',
  31. 'did-frame-navigate',
  32. 'did-navigate-in-page',
  33. 'focus-change',
  34. 'close',
  35. 'crashed',
  36. 'gpu-crashed',
  37. 'plugin-crashed',
  38. 'destroyed',
  39. 'page-title-updated',
  40. 'page-favicon-updated',
  41. 'enter-html-full-screen',
  42. 'leave-html-full-screen',
  43. 'media-started-playing',
  44. 'media-paused',
  45. 'found-in-page',
  46. 'did-change-theme-color',
  47. 'update-target-url'
  48. ]
  49. let nextGuestInstanceId = 0
  50. const guestInstances = {}
  51. const embedderElementsMap = {}
  52. // Generate guestInstanceId.
  53. const getNextGuestInstanceId = function () {
  54. return ++nextGuestInstanceId
  55. }
  56. // Create a new guest instance.
  57. const createGuest = function (embedder, params) {
  58. if (webViewManager == null) {
  59. webViewManager = process.atomBinding('web_view_manager')
  60. }
  61. const guestInstanceId = getNextGuestInstanceId(embedder)
  62. const guest = webContents.create({
  63. isGuest: true,
  64. partition: params.partition,
  65. embedder: embedder
  66. })
  67. guestInstances[guestInstanceId] = {
  68. guest: guest,
  69. embedder: embedder
  70. }
  71. // Clear the guest from map when it is destroyed.
  72. //
  73. // The guest WebContents is usually destroyed in 2 cases:
  74. // 1. The embedder frame is closed (reloaded or destroyed), and it
  75. // automatically closes the guest frame.
  76. // 2. The guest frame is detached dynamically via JS, and it is manually
  77. // destroyed when the renderer sends the GUEST_VIEW_MANAGER_DESTROY_GUEST
  78. // message.
  79. // The second case relies on the libcc patch:
  80. // https://github.com/electron/libchromiumcontent/pull/676
  81. // The patch was introduced to work around a bug in Chromium:
  82. // https://github.com/electron/electron/issues/14211
  83. // We should revisit the bug to see if we can remove our libcc patch, the
  84. // patch was introduced in Chrome 66.
  85. guest.once('destroyed', () => {
  86. if (guestInstanceId in guestInstances) {
  87. detachGuest(embedder, guestInstanceId)
  88. }
  89. })
  90. // Init guest web view after attached.
  91. guest.once('did-attach', function (event) {
  92. params = this.attachParams
  93. delete this.attachParams
  94. const previouslyAttached = this.viewInstanceId != null
  95. this.viewInstanceId = params.instanceId
  96. // Only load URL and set size on first attach
  97. if (previouslyAttached) {
  98. return
  99. }
  100. if (params.src) {
  101. const opts = {}
  102. if (params.httpreferrer) {
  103. opts.httpReferrer = params.httpreferrer
  104. }
  105. if (params.useragent) {
  106. opts.userAgent = params.useragent
  107. }
  108. this.loadURL(params.src, opts)
  109. }
  110. guest.allowPopups = params.allowpopups
  111. embedder.emit('did-attach-webview', event, guest)
  112. })
  113. const sendToEmbedder = (channel, ...args) => {
  114. if (!embedder.isDestroyed()) {
  115. embedder._sendInternal(`${channel}-${guest.viewInstanceId}`, ...args)
  116. }
  117. }
  118. // Dispatch events to embedder.
  119. const fn = function (event) {
  120. guest.on(event, function (_, ...args) {
  121. sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT', event, ...args)
  122. })
  123. }
  124. for (const event of supportedWebViewEvents) {
  125. fn(event)
  126. }
  127. // Dispatch guest's IPC messages to embedder.
  128. guest.on('ipc-message-host', function (_, [channel, ...args]) {
  129. sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE', channel, ...args)
  130. })
  131. // Notify guest of embedder window visibility when it is ready
  132. // FIXME Remove once https://github.com/electron/electron/issues/6828 is fixed
  133. guest.on('dom-ready', function () {
  134. const guestInstance = guestInstances[guestInstanceId]
  135. if (guestInstance != null && guestInstance.visibilityState != null) {
  136. guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', guestInstance.visibilityState)
  137. }
  138. })
  139. // Forward internal web contents event to embedder to handle
  140. // native window.open setup
  141. guest.on('-add-new-contents', (...args) => {
  142. if (guest.getLastWebPreferences().nativeWindowOpen === true) {
  143. const embedder = getEmbedder(guestInstanceId)
  144. if (embedder != null) {
  145. embedder.emit('-add-new-contents', ...args)
  146. }
  147. }
  148. })
  149. guest.on('-web-contents-created', (...args) => {
  150. if (guest.getLastWebPreferences().nativeWindowOpen === true) {
  151. const embedder = getEmbedder(guestInstanceId)
  152. if (embedder != null) {
  153. embedder.emit('-web-contents-created', ...args)
  154. }
  155. }
  156. })
  157. return guestInstanceId
  158. }
  159. // Attach the guest to an element of embedder.
  160. const attachGuest = function (event, embedderFrameId, elementInstanceId, guestInstanceId, params) {
  161. const embedder = event.sender
  162. // Destroy the old guest when attaching.
  163. const key = `${embedder.id}-${elementInstanceId}`
  164. const oldGuestInstanceId = embedderElementsMap[key]
  165. if (oldGuestInstanceId != null) {
  166. // Reattachment to the same guest is just a no-op.
  167. if (oldGuestInstanceId === guestInstanceId) {
  168. return
  169. }
  170. const oldGuestInstance = guestInstances[oldGuestInstanceId]
  171. if (oldGuestInstance) {
  172. oldGuestInstance.guest.destroy()
  173. }
  174. }
  175. const guestInstance = guestInstances[guestInstanceId]
  176. // If this isn't a valid guest instance then do nothing.
  177. if (!guestInstance) {
  178. throw new Error(`Invalid guestInstanceId: ${guestInstanceId}`)
  179. }
  180. const { guest } = guestInstance
  181. if (guest.hostWebContents !== event.sender) {
  182. throw new Error(`Access denied to guestInstanceId: ${guestInstanceId}`)
  183. }
  184. // If this guest is already attached to an element then remove it
  185. if (guestInstance.elementInstanceId) {
  186. const oldKey = `${guestInstance.embedder.id}-${guestInstance.elementInstanceId}`
  187. delete embedderElementsMap[oldKey]
  188. // Remove guest from embedder if moving across web views
  189. if (guest.viewInstanceId !== params.instanceId) {
  190. webViewManager.removeGuest(guestInstance.embedder, guestInstanceId)
  191. guestInstance.embedder._sendInternal(`ELECTRON_GUEST_VIEW_INTERNAL_DESTROY_GUEST-${guest.viewInstanceId}`)
  192. }
  193. }
  194. const webPreferences = {
  195. guestInstanceId: guestInstanceId,
  196. nodeIntegration: params.nodeintegration != null ? params.nodeintegration : false,
  197. enableRemoteModule: params.enableremotemodule,
  198. plugins: params.plugins,
  199. zoomFactor: embedder._getZoomFactor(),
  200. webSecurity: !params.disablewebsecurity,
  201. enableBlinkFeatures: params.blinkfeatures,
  202. disableBlinkFeatures: params.disableblinkfeatures
  203. }
  204. // parse the 'webpreferences' attribute string, if set
  205. // this uses the same parsing rules as window.open uses for its features
  206. if (typeof params.webpreferences === 'string') {
  207. parseFeaturesString(params.webpreferences, function (key, value) {
  208. if (value === undefined) {
  209. // no value was specified, default it to true
  210. value = true
  211. }
  212. webPreferences[key] = value
  213. })
  214. }
  215. if (params.preload) {
  216. webPreferences.preloadURL = params.preload
  217. }
  218. // Return null from native window.open if allowpopups is unset
  219. if (webPreferences.nativeWindowOpen === true && !params.allowpopups) {
  220. webPreferences.disablePopups = true
  221. }
  222. // Security options that guest will always inherit from embedder
  223. const inheritedWebPreferences = new Map([
  224. ['contextIsolation', true],
  225. ['javascript', false],
  226. ['nativeWindowOpen', true],
  227. ['nodeIntegration', false],
  228. ['enableRemoteModule', false],
  229. ['sandbox', true]
  230. ])
  231. // Inherit certain option values from embedder
  232. const lastWebPreferences = embedder.getLastWebPreferences()
  233. for (const [name, value] of inheritedWebPreferences) {
  234. if (lastWebPreferences[name] === value) {
  235. webPreferences[name] = value
  236. }
  237. }
  238. embedder.emit('will-attach-webview', event, webPreferences, params)
  239. if (event.defaultPrevented) {
  240. if (guest.viewInstanceId == null) guest.viewInstanceId = params.instanceId
  241. guest.destroy()
  242. return
  243. }
  244. guest.attachParams = params
  245. embedderElementsMap[key] = guestInstanceId
  246. guest.setEmbedder(embedder)
  247. guestInstance.embedder = embedder
  248. guestInstance.elementInstanceId = elementInstanceId
  249. watchEmbedder(embedder)
  250. webViewManager.addGuest(guestInstanceId, elementInstanceId, embedder, guest, webPreferences)
  251. guest.attachToIframe(embedder, embedderFrameId)
  252. }
  253. // Remove an guest-embedder relationship.
  254. const detachGuest = function (embedder, guestInstanceId) {
  255. const guestInstance = guestInstances[guestInstanceId]
  256. if (embedder !== guestInstance.embedder) {
  257. return
  258. }
  259. webViewManager.removeGuest(embedder, guestInstanceId)
  260. delete guestInstances[guestInstanceId]
  261. const key = `${embedder.id}-${guestInstance.elementInstanceId}`
  262. delete embedderElementsMap[key]
  263. }
  264. // Once an embedder has had a guest attached we watch it for destruction to
  265. // destroy any remaining guests.
  266. const watchedEmbedders = new Set()
  267. const watchEmbedder = function (embedder) {
  268. if (watchedEmbedders.has(embedder)) {
  269. return
  270. }
  271. watchedEmbedders.add(embedder)
  272. // Forward embedder window visiblity change events to guest
  273. const onVisibilityChange = function (visibilityState) {
  274. for (const guestInstanceId in guestInstances) {
  275. const guestInstance = guestInstances[guestInstanceId]
  276. guestInstance.visibilityState = visibilityState
  277. if (guestInstance.embedder === embedder) {
  278. guestInstance.guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', visibilityState)
  279. }
  280. }
  281. }
  282. embedder.on('-window-visibility-change', onVisibilityChange)
  283. embedder.once('will-destroy', () => {
  284. // Usually the guestInstances is cleared when guest is destroyed, but it
  285. // may happen that the embedder gets manually destroyed earlier than guest,
  286. // and the embedder will be invalid in the usual code path.
  287. for (const guestInstanceId in guestInstances) {
  288. const guestInstance = guestInstances[guestInstanceId]
  289. if (guestInstance.embedder === embedder) {
  290. detachGuest(embedder, parseInt(guestInstanceId))
  291. }
  292. }
  293. // Clear the listeners.
  294. embedder.removeListener('-window-visibility-change', onVisibilityChange)
  295. watchedEmbedders.delete(embedder)
  296. })
  297. }
  298. const isWebViewTagEnabledCache = new WeakMap()
  299. const isWebViewTagEnabled = function (contents) {
  300. if (!isWebViewTagEnabledCache.has(contents)) {
  301. const value = contents.getLastWebPreferences().webviewTag
  302. isWebViewTagEnabledCache.set(contents, value)
  303. }
  304. return isWebViewTagEnabledCache.get(contents)
  305. }
  306. const handleMessage = function (channel, handler) {
  307. ipcMain.on(channel, (event, ...args) => {
  308. if (isWebViewTagEnabled(event.sender)) {
  309. handler(event, ...args)
  310. } else {
  311. event.returnValue = null
  312. }
  313. })
  314. }
  315. handleMessage('ELECTRON_GUEST_VIEW_MANAGER_CREATE_GUEST', function (event, params, requestId) {
  316. event.sender._sendInternal(`ELECTRON_RESPONSE_${requestId}`, createGuest(event.sender, params))
  317. })
  318. handleMessage('ELECTRON_GUEST_VIEW_MANAGER_CREATE_GUEST_SYNC', function (event, params) {
  319. event.returnValue = createGuest(event.sender, params)
  320. })
  321. handleMessage('ELECTRON_GUEST_VIEW_MANAGER_DESTROY_GUEST', function (event, guestInstanceId) {
  322. try {
  323. const guest = getGuestForWebContents(guestInstanceId, event.sender)
  324. guest.destroy()
  325. } catch (error) {
  326. console.error(`Guest destroy failed: ${error}`)
  327. }
  328. })
  329. handleMessage('ELECTRON_GUEST_VIEW_MANAGER_ATTACH_GUEST', function (event, embedderFrameId, elementInstanceId, guestInstanceId, params) {
  330. try {
  331. attachGuest(event, embedderFrameId, elementInstanceId, guestInstanceId, params)
  332. } catch (error) {
  333. console.error(`Guest attach failed: ${error}`)
  334. }
  335. })
  336. // this message is sent by the actual <webview>
  337. ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_FOCUS_CHANGE', function (event, focus, guestInstanceId) {
  338. const guest = getGuest(guestInstanceId)
  339. if (guest === event.sender) {
  340. event.sender.emit('focus-change', {}, focus, guestInstanceId)
  341. } else {
  342. console.error(`focus-change for guestInstanceId: ${guestInstanceId}`)
  343. }
  344. })
  345. handleMessage('ELECTRON_GUEST_VIEW_MANAGER_ASYNC_CALL', function (event, requestId, guestInstanceId, method, args, hasCallback) {
  346. new Promise(resolve => {
  347. const guest = getGuestForWebContents(guestInstanceId, event.sender)
  348. if (!asyncCallbackMethods.has(method) && !asyncPromiseMethods.has(method)) {
  349. throw new Error(`Invalid method: ${method}`)
  350. }
  351. if (hasCallback) {
  352. guest[method](...args, resolve)
  353. } else {
  354. resolve(guest[method](...args))
  355. }
  356. }).then(result => {
  357. return [null, result]
  358. }, error => {
  359. return [errorUtils.serialize(error)]
  360. }).then(responseArgs => {
  361. event.sender._sendInternal(`ELECTRON_GUEST_VIEW_MANAGER_ASYNC_CALL_RESPONSE_${requestId}`, ...responseArgs)
  362. })
  363. })
  364. handleMessage('ELECTRON_GUEST_VIEW_MANAGER_SYNC_CALL', function (event, guestInstanceId, method, args) {
  365. try {
  366. const guest = getGuestForWebContents(guestInstanceId, event.sender)
  367. if (!syncMethods.has(method)) {
  368. throw new Error(`Invalid method: ${method}`)
  369. }
  370. event.returnValue = [null, guest[method](...args)]
  371. } catch (error) {
  372. event.returnValue = [errorUtils.serialize(error)]
  373. }
  374. })
  375. // Returns WebContents from its guest id hosted in given webContents.
  376. const getGuestForWebContents = function (guestInstanceId, contents) {
  377. const guest = getGuest(guestInstanceId)
  378. if (!guest) {
  379. throw new Error(`Invalid guestInstanceId: ${guestInstanceId}`)
  380. }
  381. if (guest.hostWebContents !== contents) {
  382. throw new Error(`Access denied to guestInstanceId: ${guestInstanceId}`)
  383. }
  384. return guest
  385. }
  386. // Returns WebContents from its guest id.
  387. const getGuest = function (guestInstanceId) {
  388. const guestInstance = guestInstances[guestInstanceId]
  389. if (guestInstance != null) return guestInstance.guest
  390. }
  391. // Returns the embedder of the guest.
  392. const getEmbedder = function (guestInstanceId) {
  393. const guestInstance = guestInstances[guestInstanceId]
  394. if (guestInstance != null) return guestInstance.embedder
  395. }
  396. exports.getGuestForWebContents = getGuestForWebContents