guest-view-manager.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. 'use strict'
  2. const {ipcMain, webContents} = require('electron')
  3. const parseFeaturesString = require('../common/parse-features-string')
  4. // Doesn't exist in early initialization.
  5. let webViewManager = null
  6. const supportedWebViewEvents = [
  7. 'load-commit',
  8. 'did-attach',
  9. 'did-finish-load',
  10. 'did-fail-load',
  11. 'did-frame-finish-load',
  12. 'did-start-loading',
  13. 'did-stop-loading',
  14. '-did-get-response-details',
  15. '-did-get-redirect-request',
  16. 'dom-ready',
  17. 'console-message',
  18. 'context-menu',
  19. 'devtools-opened',
  20. 'devtools-closed',
  21. 'devtools-focused',
  22. 'new-window',
  23. 'will-navigate',
  24. 'did-start-navigation',
  25. 'did-navigate',
  26. 'did-frame-navigate',
  27. 'did-navigate-in-page',
  28. 'close',
  29. 'crashed',
  30. 'gpu-crashed',
  31. 'plugin-crashed',
  32. 'destroyed',
  33. 'page-title-updated',
  34. 'page-favicon-updated',
  35. 'enter-html-full-screen',
  36. 'leave-html-full-screen',
  37. 'media-started-playing',
  38. 'media-paused',
  39. 'found-in-page',
  40. 'did-change-theme-color',
  41. 'update-target-url'
  42. ]
  43. let nextGuestInstanceId = 0
  44. const guestInstances = {}
  45. const embedderElementsMap = {}
  46. // Moves the last element of array to the first one.
  47. const moveLastToFirst = function (list) {
  48. list.unshift(list.pop())
  49. }
  50. // Generate guestInstanceId.
  51. const getNextGuestInstanceId = function () {
  52. return ++nextGuestInstanceId
  53. }
  54. // Create a new guest instance.
  55. const createGuest = function (embedder, params) {
  56. if (webViewManager == null) {
  57. webViewManager = process.atomBinding('web_view_manager')
  58. }
  59. const guestInstanceId = getNextGuestInstanceId(embedder)
  60. const guest = webContents.create({
  61. isGuest: true,
  62. partition: params.partition,
  63. embedder: embedder
  64. })
  65. guestInstances[guestInstanceId] = {
  66. guest: guest,
  67. embedder: embedder
  68. }
  69. watchEmbedder(embedder)
  70. // Init guest web view after attached.
  71. guest.on('did-attach', function (event) {
  72. params = this.attachParams
  73. delete this.attachParams
  74. const previouslyAttached = this.viewInstanceId != null
  75. this.viewInstanceId = params.instanceId
  76. // Only load URL and set size on first attach
  77. if (previouslyAttached) {
  78. return
  79. }
  80. this.setSize({
  81. normal: {
  82. width: params.elementWidth,
  83. height: params.elementHeight
  84. },
  85. enableAutoSize: params.autosize,
  86. min: {
  87. width: params.minwidth,
  88. height: params.minheight
  89. },
  90. max: {
  91. width: params.maxwidth,
  92. height: params.maxheight
  93. }
  94. })
  95. if (params.src) {
  96. const opts = {}
  97. if (params.httpreferrer) {
  98. opts.httpReferrer = params.httpreferrer
  99. }
  100. if (params.useragent) {
  101. opts.userAgent = params.useragent
  102. }
  103. this.loadURL(params.src, opts)
  104. }
  105. guest.allowPopups = params.allowpopups
  106. embedder.emit('did-attach-webview', event, guest)
  107. })
  108. const sendToEmbedder = (channel, ...args) => {
  109. const embedder = getEmbedder(guestInstanceId)
  110. if (embedder != null) {
  111. embedder.send(`${channel}-${guest.viewInstanceId}`, ...args)
  112. }
  113. }
  114. // Dispatch events to embedder.
  115. const fn = function (event) {
  116. guest.on(event, function (_, ...args) {
  117. sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT', event, ...args)
  118. })
  119. }
  120. for (const event of supportedWebViewEvents) {
  121. fn(event)
  122. }
  123. // Dispatch guest's IPC messages to embedder.
  124. guest.on('ipc-message-host', function (_, [channel, ...args]) {
  125. sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE', channel, ...args)
  126. })
  127. // Autosize.
  128. guest.on('size-changed', function (_, ...args) {
  129. sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_SIZE_CHANGED', ...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.send('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, elementInstanceId, guestInstanceId, params) {
  161. const embedder = event.sender
  162. // Destroy the old guest when attaching.
  163. const key = `${embedder.getId()}-${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. destroyGuest(embedder, oldGuestInstanceId)
  171. }
  172. const guestInstance = guestInstances[guestInstanceId]
  173. // If this isn't a valid guest instance then do nothing.
  174. if (!guestInstance) {
  175. return
  176. }
  177. const {guest} = guestInstance
  178. // If this guest is already attached to an element then remove it
  179. if (guestInstance.elementInstanceId) {
  180. const oldKey = `${guestInstance.embedder.getId()}-${guestInstance.elementInstanceId}`
  181. delete embedderElementsMap[oldKey]
  182. // Remove guest from embedder if moving across web views
  183. if (guest.viewInstanceId !== params.instanceId) {
  184. webViewManager.removeGuest(guestInstance.embedder, guestInstanceId)
  185. guestInstance.embedder.send(`ELECTRON_GUEST_VIEW_INTERNAL_DESTROY_GUEST-${guest.viewInstanceId}`)
  186. }
  187. }
  188. const webPreferences = {
  189. guestInstanceId: guestInstanceId,
  190. nodeIntegration: params.nodeintegration != null ? params.nodeintegration : false,
  191. plugins: params.plugins,
  192. zoomFactor: embedder._getZoomFactor(),
  193. webSecurity: !params.disablewebsecurity,
  194. enableBlinkFeatures: params.blinkfeatures,
  195. disableBlinkFeatures: params.disableblinkfeatures
  196. }
  197. // parse the 'webpreferences' attribute string, if set
  198. // this uses the same parsing rules as window.open uses for its features
  199. if (typeof params.webpreferences === 'string') {
  200. parseFeaturesString(params.webpreferences, function (key, value) {
  201. if (value === undefined) {
  202. // no value was specified, default it to true
  203. value = true
  204. }
  205. webPreferences[key] = value
  206. })
  207. }
  208. if (params.preload) {
  209. webPreferences.preloadURL = params.preload
  210. }
  211. // Return null from native window.open if allowpopups is unset
  212. if (webPreferences.nativeWindowOpen === true && !params.allowpopups) {
  213. webPreferences.disablePopups = true
  214. }
  215. embedder.emit('will-attach-webview', event, webPreferences, params)
  216. if (event.defaultPrevented) {
  217. if (guest.viewInstanceId == null) guest.viewInstanceId = params.instanceId
  218. destroyGuest(embedder, guestInstanceId)
  219. return
  220. }
  221. webViewManager.addGuest(guestInstanceId, elementInstanceId, embedder, guest, webPreferences)
  222. guest.attachParams = params
  223. embedderElementsMap[key] = guestInstanceId
  224. guest.setEmbedder(embedder)
  225. guestInstance.embedder = embedder
  226. guestInstance.elementInstanceId = elementInstanceId
  227. watchEmbedder(embedder)
  228. }
  229. // Destroy an existing guest instance.
  230. const destroyGuest = function (embedder, guestInstanceId) {
  231. if (!(guestInstanceId in guestInstances)) {
  232. return
  233. }
  234. const guestInstance = guestInstances[guestInstanceId]
  235. if (embedder !== guestInstance.embedder) {
  236. return
  237. }
  238. webViewManager.removeGuest(embedder, guestInstanceId)
  239. guestInstance.guest.destroy()
  240. delete guestInstances[guestInstanceId]
  241. const key = `${embedder.getId()}-${guestInstance.elementInstanceId}`
  242. delete embedderElementsMap[key]
  243. }
  244. // Once an embedder has had a guest attached we watch it for destruction to
  245. // destroy any remaining guests.
  246. const watchedEmbedders = new Set()
  247. const watchEmbedder = function (embedder) {
  248. if (watchedEmbedders.has(embedder)) {
  249. return
  250. }
  251. watchedEmbedders.add(embedder)
  252. // Forward embedder window visiblity change events to guest
  253. const onVisibilityChange = function (visibilityState) {
  254. for (const guestInstanceId of Object.keys(guestInstances)) {
  255. const guestInstance = guestInstances[guestInstanceId]
  256. guestInstance.visibilityState = visibilityState
  257. if (guestInstance.embedder === embedder) {
  258. guestInstance.guest.send('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', visibilityState)
  259. }
  260. }
  261. }
  262. embedder.on('-window-visibility-change', onVisibilityChange)
  263. const destroyEvents = ['will-destroy', 'crashed', 'did-navigate']
  264. const destroy = function () {
  265. for (const guestInstanceId of Object.keys(guestInstances)) {
  266. if (guestInstances[guestInstanceId].embedder === embedder) {
  267. destroyGuest(embedder, parseInt(guestInstanceId))
  268. }
  269. }
  270. for (const event of destroyEvents) {
  271. embedder.removeListener(event, destroy)
  272. }
  273. embedder.removeListener('-window-visibility-change', onVisibilityChange)
  274. watchedEmbedders.delete(embedder)
  275. }
  276. for (const event of destroyEvents) {
  277. embedder.once(event, destroy)
  278. // Users might also listen to the crashed event, so we must ensure the guest
  279. // is destroyed before users' listener gets called. It is done by moving our
  280. // listener to the first one in queue.
  281. const listeners = embedder._events[event]
  282. if (Array.isArray(listeners)) {
  283. moveLastToFirst(listeners)
  284. }
  285. }
  286. }
  287. ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_CREATE_GUEST', function (event, params, requestId) {
  288. event.sender.send(`ELECTRON_RESPONSE_${requestId}`, createGuest(event.sender, params))
  289. })
  290. ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_ATTACH_GUEST', function (event, elementInstanceId, guestInstanceId, params) {
  291. attachGuest(event, elementInstanceId, guestInstanceId, params)
  292. })
  293. ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_DESTROY_GUEST', function (event, guestInstanceId) {
  294. destroyGuest(event.sender, guestInstanceId)
  295. })
  296. ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_SET_SIZE', function (event, guestInstanceId, params) {
  297. const guest = getGuest(guestInstanceId)
  298. if (guest != null) guest.setSize(params)
  299. })
  300. // Returns WebContents from its guest id.
  301. const getGuest = function (guestInstanceId) {
  302. const guestInstance = guestInstances[guestInstanceId]
  303. if (guestInstance != null) return guestInstance.guest
  304. }
  305. // Returns the embedder of the guest.
  306. const getEmbedder = function (guestInstanceId) {
  307. const guestInstance = guestInstances[guestInstanceId]
  308. if (guestInstance != null) return guestInstance.embedder
  309. }
  310. exports.getGuest = getGuest
  311. exports.getEmbedder = getEmbedder