electron/lib/browser/guest-view-manager.js

415 lines
13 KiB
JavaScript
Raw Normal View History

'use strict'
2016-03-18 18:51:02 +00:00
const { webContents } = require('electron')
const { ipcMainInternal } = require('@electron/internal/browser/ipc-main-internal')
const ipcMainUtils = require('@electron/internal/browser/ipc-main-internal-utils')
const parseFeaturesString = require('@electron/internal/common/parse-features-string')
const {
syncMethods,
asyncCallbackMethods,
asyncPromiseMethods
} = require('@electron/internal/common/web-view-methods')
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Doesn't exist in early initialization.
2016-06-07 17:29:24 +00:00
let webViewManager = null
2016-01-12 02:40:23 +00:00
2016-06-07 17:29:24 +00:00
const supportedWebViewEvents = [
2016-01-25 16:37:15 +00:00
'load-commit',
'did-attach',
2016-01-25 16:37:15 +00:00
'did-finish-load',
'did-fail-load',
'did-frame-finish-load',
'did-start-loading',
'did-stop-loading',
'dom-ready',
'console-message',
'context-menu',
2016-01-25 16:37:15 +00:00
'devtools-opened',
'devtools-closed',
'devtools-focused',
'new-window',
'will-navigate',
'did-start-navigation',
2016-01-25 16:37:15 +00:00
'did-navigate',
'did-frame-navigate',
2016-01-25 16:37:15 +00:00
'did-navigate-in-page',
'focus-change',
2016-01-25 16:37:15 +00:00
'close',
'crashed',
'plugin-crashed',
'destroyed',
'page-title-updated',
'page-favicon-updated',
'enter-html-full-screen',
'leave-html-full-screen',
'media-started-playing',
'media-paused',
'found-in-page',
2016-06-07 06:56:19 +00:00
'did-change-theme-color',
'update-target-url'
]
2016-01-12 02:40:23 +00:00
2016-06-07 17:29:24 +00:00
const guestInstances = {}
const embedderElementsMap = {}
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Create a new guest instance.
2016-06-07 17:29:24 +00:00
const createGuest = function (embedder, params) {
2016-01-12 02:40:23 +00:00
if (webViewManager == null) {
webViewManager = process.electronBinding('web_view_manager')
2016-01-12 02:40:23 +00:00
}
2016-06-07 17:24:48 +00:00
const guest = webContents.create({
type: 'webview',
2016-01-12 02:40:23 +00:00
partition: params.partition,
embedder: embedder
})
const guestInstanceId = guest.id
guestInstances[guestInstanceId] = {
2016-01-12 02:40:23 +00:00
guest: guest,
embedder: embedder
}
2016-01-12 02:40:23 +00:00
// Clear the guest from map when it is destroyed.
//
// The guest WebContents is usually destroyed in 2 cases:
// 1. The embedder frame is closed (reloaded or destroyed), and it
// automatically closes the guest frame.
// 2. The guest frame is detached dynamically via JS, and it is manually
// destroyed when the renderer sends the GUEST_VIEW_MANAGER_DESTROY_GUEST
// message.
// The second case relies on the libcc patch:
// https://github.com/electron/libchromiumcontent/pull/676
// The patch was introduced to work around a bug in Chromium:
// https://github.com/electron/electron/issues/14211
// We should revisit the bug to see if we can remove our libcc patch, the
// patch was introduced in Chrome 66.
guest.once('destroyed', () => {
if (guestInstanceId in guestInstances) {
detachGuest(embedder, guestInstanceId)
}
})
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Init guest web view after attached.
guest.once('did-attach', function (event) {
params = this.attachParams
delete this.attachParams
const previouslyAttached = this.viewInstanceId != null
this.viewInstanceId = params.instanceId
// Only load URL and set size on first attach
if (previouslyAttached) {
return
}
2016-01-12 02:40:23 +00:00
if (params.src) {
2016-11-03 17:39:40 +00:00
const opts = {}
2016-01-12 02:40:23 +00:00
if (params.httpreferrer) {
opts.httpReferrer = params.httpreferrer
2016-01-12 02:40:23 +00:00
}
if (params.useragent) {
opts.userAgent = params.useragent
2016-01-12 02:40:23 +00:00
}
this.loadURL(params.src, opts)
2016-01-12 02:40:23 +00:00
}
2017-10-06 16:31:41 +00:00
embedder.emit('did-attach-webview', event, guest)
})
2016-01-12 02:40:23 +00:00
2016-11-03 17:39:40 +00:00
const sendToEmbedder = (channel, ...args) => {
if (!embedder.isDestroyed()) {
embedder._sendInternal(`${channel}-${guest.viewInstanceId}`, ...args)
2016-11-03 17:39:40 +00:00
}
}
2016-01-14 18:35:29 +00:00
// Dispatch events to embedder.
2016-06-07 17:24:48 +00:00
const fn = function (event) {
guest.on(event, function (_, ...args) {
2016-11-03 17:39:40 +00:00
sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT', event, ...args)
})
}
2016-06-07 17:24:48 +00:00
for (const event of supportedWebViewEvents) {
fn(event)
2016-01-12 02:40:23 +00:00
}
2016-01-14 18:35:29 +00:00
// Dispatch guest's IPC messages to embedder.
guest.on('ipc-message-host', function (_, channel, args) {
2016-11-03 17:39:40 +00:00
sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE', channel, ...args)
})
2016-01-12 02:40:23 +00:00
// Notify guest of embedder window visibility when it is ready
2017-06-14 21:12:51 +00:00
// FIXME Remove once https://github.com/electron/electron/issues/6828 is fixed
guest.on('dom-ready', function () {
const guestInstance = guestInstances[guestInstanceId]
if (guestInstance != null && guestInstance.visibilityState != null) {
guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', guestInstance.visibilityState)
}
})
// Forward internal web contents event to embedder to handle
// native window.open setup
guest.on('-add-new-contents', (...args) => {
if (guest.getLastWebPreferences().nativeWindowOpen === true) {
const embedder = getEmbedder(guestInstanceId)
if (embedder != null) {
embedder.emit('-add-new-contents', ...args)
}
}
})
return guestInstanceId
}
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Attach the guest to an element of embedder.
const attachGuest = function (event, embedderFrameId, elementInstanceId, guestInstanceId, params) {
const embedder = event.sender
2016-01-14 18:35:29 +00:00
// Destroy the old guest when attaching.
const key = `${embedder.id}-${elementInstanceId}`
2016-11-03 17:39:40 +00:00
const oldGuestInstanceId = embedderElementsMap[key]
2016-01-12 02:40:23 +00:00
if (oldGuestInstanceId != null) {
// Reattachment to the same guest is just a no-op.
2016-01-12 02:40:23 +00:00
if (oldGuestInstanceId === guestInstanceId) {
return
2016-01-12 02:40:23 +00:00
}
const oldGuestInstance = guestInstances[oldGuestInstanceId]
if (oldGuestInstance) {
oldGuestInstance.guest.detachFromOuterFrame()
}
2016-01-12 02:40:23 +00:00
}
2016-11-03 17:39:40 +00:00
const guestInstance = guestInstances[guestInstanceId]
// If this isn't a valid guest instance then do nothing.
if (!guestInstance) {
throw new Error(`Invalid guestInstanceId: ${guestInstanceId}`)
}
2018-09-13 16:10:51 +00:00
const { guest } = guestInstance
if (guest.hostWebContents !== event.sender) {
throw new Error(`Access denied to guestInstanceId: ${guestInstanceId}`)
}
// If this guest is already attached to an element then remove it
if (guestInstance.elementInstanceId) {
const oldKey = `${guestInstance.embedder.id}-${guestInstance.elementInstanceId}`
delete embedderElementsMap[oldKey]
// Remove guest from embedder if moving across web views
if (guest.viewInstanceId !== params.instanceId) {
webViewManager.removeGuest(guestInstance.embedder, guestInstanceId)
guestInstance.embedder._sendInternal(`ELECTRON_GUEST_VIEW_INTERNAL_DESTROY_GUEST-${guest.viewInstanceId}`)
}
}
2016-11-03 17:39:40 +00:00
const webPreferences = {
2016-01-12 02:40:23 +00:00
guestInstanceId: guestInstanceId,
2016-11-03 17:39:40 +00:00
nodeIntegration: params.nodeintegration != null ? params.nodeintegration : false,
nodeIntegrationInSubFrames: params.nodeintegrationinsubframes != null ? params.nodeintegrationinsubframes : false,
enableRemoteModule: params.enableremotemodule,
2016-01-12 02:40:23 +00:00
plugins: params.plugins,
zoomFactor: embedder.getZoomFactor(),
disablePopups: !params.allowpopups,
2016-01-21 10:13:41 +00:00
webSecurity: !params.disablewebsecurity,
enableBlinkFeatures: params.blinkfeatures,
2016-06-07 23:35:23 +00:00
disableBlinkFeatures: params.disableblinkfeatures
}
// parse the 'webpreferences' attribute string, if set
// this uses the same parsing rules as window.open uses for its features
if (typeof params.webpreferences === 'string') {
2016-10-25 01:21:42 +00:00
parseFeaturesString(params.webpreferences, function (key, value) {
if (value === undefined) {
// no value was specified, default it to true
value = true
}
webPreferences[key] = value
2016-10-25 01:21:42 +00:00
})
}
2016-01-12 02:40:23 +00:00
if (params.preload) {
webPreferences.preloadURL = params.preload
2016-01-12 02:40:23 +00:00
}
// Security options that guest will always inherit from embedder
const inheritedWebPreferences = new Map([
['contextIsolation', true],
['javascript', false],
['nativeWindowOpen', true],
['nodeIntegration', false],
['enableRemoteModule', false],
['sandbox', true],
['nodeIntegrationInSubFrames', false]
])
// Inherit certain option values from embedder
const lastWebPreferences = embedder.getLastWebPreferences()
for (const [name, value] of inheritedWebPreferences) {
if (lastWebPreferences[name] === value) {
webPreferences[name] = value
}
}
2017-02-09 19:48:45 +00:00
embedder.emit('will-attach-webview', event, webPreferences, params)
if (event.defaultPrevented) {
if (guest.viewInstanceId == null) guest.viewInstanceId = params.instanceId
guest.destroy()
return
}
guest.attachParams = params
embedderElementsMap[key] = guestInstanceId
guest.setEmbedder(embedder)
guestInstance.embedder = embedder
guestInstance.elementInstanceId = elementInstanceId
watchEmbedder(embedder)
2016-01-12 02:40:23 +00:00
webViewManager.addGuest(guestInstanceId, elementInstanceId, embedder, guest, webPreferences)
guest.attachToIframe(embedder, embedderFrameId)
}
// Remove an guest-embedder relationship.
const detachGuest = function (embedder, guestInstanceId) {
2016-11-03 17:39:40 +00:00
const guestInstance = guestInstances[guestInstanceId]
if (embedder !== guestInstance.embedder) {
return
}
webViewManager.removeGuest(embedder, guestInstanceId)
delete guestInstances[guestInstanceId]
const key = `${embedder.id}-${guestInstance.elementInstanceId}`
2016-11-03 17:19:52 +00:00
delete embedderElementsMap[key]
}
// Once an embedder has had a guest attached we watch it for destruction to
// destroy any remaining guests.
const watchedEmbedders = new Set()
const watchEmbedder = function (embedder) {
if (watchedEmbedders.has(embedder)) {
return
}
watchedEmbedders.add(embedder)
// Forward embedder window visiblity change events to guest
const onVisibilityChange = function (visibilityState) {
for (const guestInstanceId in guestInstances) {
const guestInstance = guestInstances[guestInstanceId]
guestInstance.visibilityState = visibilityState
if (guestInstance.embedder === embedder) {
guestInstance.guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', visibilityState)
}
}
}
embedder.on('-window-visibility-change', onVisibilityChange)
embedder.once('will-destroy', () => {
// Usually the guestInstances is cleared when guest is destroyed, but it
// may happen that the embedder gets manually destroyed earlier than guest,
// and the embedder will be invalid in the usual code path.
for (const guestInstanceId in guestInstances) {
const guestInstance = guestInstances[guestInstanceId]
if (guestInstance.embedder === embedder) {
detachGuest(embedder, parseInt(guestInstanceId))
}
}
// Clear the listeners.
embedder.removeListener('-window-visibility-change', onVisibilityChange)
watchedEmbedders.delete(embedder)
})
}
2016-01-12 02:40:23 +00:00
const isWebViewTagEnabledCache = new WeakMap()
const isWebViewTagEnabled = function (contents) {
if (!isWebViewTagEnabledCache.has(contents)) {
const webPreferences = contents.getLastWebPreferences() || {}
isWebViewTagEnabledCache.set(contents, !!webPreferences.webviewTag)
}
return isWebViewTagEnabledCache.get(contents)
}
const handleMessage = function (channel, handler) {
ipcMainUtils.handle(channel, (event, ...args) => {
if (isWebViewTagEnabled(event.sender)) {
return handler(event, ...args)
} else {
console.error(`<webview> IPC message ${channel} sent by WebContents with <webview> disabled (${event.sender.id})`)
throw new Error('<webview> disabled')
}
})
}
handleMessage('ELECTRON_GUEST_VIEW_MANAGER_CREATE_GUEST', function (event, params) {
return createGuest(event.sender, params)
})
handleMessage('ELECTRON_GUEST_VIEW_MANAGER_DESTROY_GUEST', function (event, guestInstanceId) {
try {
const guest = getGuestForWebContents(guestInstanceId, event.sender)
guest.detachFromOuterFrame()
} catch (error) {
console.error(`Guest destroy failed: ${error}`)
}
})
handleMessage('ELECTRON_GUEST_VIEW_MANAGER_ATTACH_GUEST', function (event, embedderFrameId, elementInstanceId, guestInstanceId, params) {
try {
attachGuest(event, embedderFrameId, elementInstanceId, guestInstanceId, params)
} catch (error) {
console.error(`Guest attach failed: ${error}`)
}
})
2016-01-12 02:40:23 +00:00
// this message is sent by the actual <webview>
ipcMainInternal.on('ELECTRON_GUEST_VIEW_MANAGER_FOCUS_CHANGE', function (event, focus, guestInstanceId) {
const guest = getGuest(guestInstanceId)
if (guest === event.sender) {
event.sender.emit('focus-change', {}, focus, guestInstanceId)
} else {
console.error(`focus-change for guestInstanceId: ${guestInstanceId}`)
}
})
const allMethods = new Set([
...syncMethods,
...asyncCallbackMethods,
...asyncPromiseMethods
])
handleMessage('ELECTRON_GUEST_VIEW_MANAGER_CALL', function (event, guestInstanceId, method, args) {
const guest = getGuestForWebContents(guestInstanceId, event.sender)
if (!allMethods.has(method)) {
throw new Error(`Invalid method: ${method}`)
}
return guest[method](...args)
})
// Returns WebContents from its guest id hosted in given webContents.
const getGuestForWebContents = function (guestInstanceId, contents) {
const guest = getGuest(guestInstanceId)
if (!guest) {
throw new Error(`Invalid guestInstanceId: ${guestInstanceId}`)
}
if (guest.hostWebContents !== contents) {
throw new Error(`Access denied to guestInstanceId: ${guestInstanceId}`)
}
return guest
}
2016-01-14 18:35:29 +00:00
// Returns WebContents from its guest id.
2016-11-03 17:39:40 +00:00
const getGuest = function (guestInstanceId) {
const guestInstance = guestInstances[guestInstanceId]
if (guestInstance != null) return guestInstance.guest
}
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Returns the embedder of the guest.
const getEmbedder = function (guestInstanceId) {
const guestInstance = guestInstances[guestInstanceId]
if (guestInstance != null) return guestInstance.embedder
}
2016-11-03 17:39:40 +00:00
exports.getGuestForWebContents = getGuestForWebContents
exports.isWebViewTagEnabled = isWebViewTagEnabled