guest-view-manager.js 14 KB

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