guest-view-manager.js 13 KB

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