guest-view-manager.js 14 KB

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