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

391 lines
14 KiB
TypeScript
Raw Normal View History

import { webContents } from 'electron/main';
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils';
import { parseWebViewWebPreferences } from '@electron/internal/browser/parse-features-string';
import { syncMethods, asyncMethods, properties } from '@electron/internal/common/web-view-methods';
import { webViewEvents } from '@electron/internal/browser/web-view-events';
import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
interface GuestInstance {
elementInstanceId?: number;
visibilityState?: VisibilityState;
embedder: Electron.WebContents;
guest: Electron.WebContents;
}
2016-01-12 02:40:23 +00:00
const webViewManager = process._linkedBinding('electron_browser_web_view_manager');
const eventBinding = process._linkedBinding('electron_browser_event');
2016-01-12 02:40:23 +00:00
const supportedWebViewEvents = Object.keys(webViewEvents);
2016-01-12 02:40:23 +00:00
const guestInstances = new Map<number, GuestInstance>();
const embedderElementsMap = new Map<string, number>();
2016-01-12 02:40:23 +00:00
function sanitizeOptionsForGuest (options: Record<string, any>) {
2020-03-20 20:28:31 +00:00
const ret = { ...options };
refactor: use v8 serialization for ipc (#20214) * refactor: use v8 serialization for ipc * cloning process.env doesn't work * serialize host objects by enumerating key/values * new serialization can handle NaN, Infinity, and undefined correctly * can't allocate v8 objects during GC * backport microtasks fix * fix compile * fix node_stream_loader reentrancy * update subframe spec to expect undefined instead of null * write undefined instead of crashing when serializing host objects * fix webview spec * fix download spec * buffers are transformed into uint8arrays * can't serialize promises * fix chrome.i18n.getMessage * fix devtools tests * fix zoom test * fix debug build * fix lint * update ipcRenderer tests * fix printToPDF test * update patch * remove accidentally re-added remote-side spec * wip * don't attempt to serialize host objects * jump through different hoops to set options.webContents sometimes * whoops * fix lint * clean up error-handling logic * fix memory leak * fix lint * convert host objects using old base::Value serialization * fix lint more * fall back to base::Value-based serialization * remove commented-out code * add docs to breaking-changes.md * Update breaking-changes.md * update ipcRenderer and WebContents docs * lint * use named values for format tag * save a memcpy for ~30% speedup * get rid of calls to ShallowClone * extra debugging for paranoia * d'oh, use the correct named tags * apparently msstl doesn't like this DCHECK * funny story about that DCHECK * disable remote-related functions when enable_remote_module = false * nits * use EnableIf to disable remote methods in mojom * fix include * review comments
2019-10-09 17:59:08 +00:00
// WebContents values can't be sent over IPC.
2020-03-20 20:28:31 +00:00
delete ret.webContents;
return ret;
refactor: use v8 serialization for ipc (#20214) * refactor: use v8 serialization for ipc * cloning process.env doesn't work * serialize host objects by enumerating key/values * new serialization can handle NaN, Infinity, and undefined correctly * can't allocate v8 objects during GC * backport microtasks fix * fix compile * fix node_stream_loader reentrancy * update subframe spec to expect undefined instead of null * write undefined instead of crashing when serializing host objects * fix webview spec * fix download spec * buffers are transformed into uint8arrays * can't serialize promises * fix chrome.i18n.getMessage * fix devtools tests * fix zoom test * fix debug build * fix lint * update ipcRenderer tests * fix printToPDF test * update patch * remove accidentally re-added remote-side spec * wip * don't attempt to serialize host objects * jump through different hoops to set options.webContents sometimes * whoops * fix lint * clean up error-handling logic * fix memory leak * fix lint * convert host objects using old base::Value serialization * fix lint more * fall back to base::Value-based serialization * remove commented-out code * add docs to breaking-changes.md * Update breaking-changes.md * update ipcRenderer and WebContents docs * lint * use named values for format tag * save a memcpy for ~30% speedup * get rid of calls to ShallowClone * extra debugging for paranoia * d'oh, use the correct named tags * apparently msstl doesn't like this DCHECK * funny story about that DCHECK * disable remote-related functions when enable_remote_module = false * nits * use EnableIf to disable remote methods in mojom * fix include * review comments
2019-10-09 17:59:08 +00:00
}
function makeWebPreferences (embedder: Electron.WebContents, params: Record<string, any>) {
// parse the 'webpreferences' attribute string, if set
// this uses the same parsing rules as window.open uses for its features
const parsedWebPreferences =
typeof params.webpreferences === 'string'
? parseWebViewWebPreferences(params.webpreferences)
: null;
const webPreferences: Electron.WebPreferences = {
nodeIntegration: params.nodeintegration != null ? params.nodeintegration : false,
nodeIntegrationInSubFrames: params.nodeintegrationinsubframes != null ? params.nodeintegrationinsubframes : false,
plugins: params.plugins,
zoomFactor: embedder.zoomFactor,
disablePopups: !params.allowpopups,
webSecurity: !params.disablewebsecurity,
enableBlinkFeatures: params.blinkfeatures,
disableBlinkFeatures: params.disableblinkfeatures,
...parsedWebPreferences
};
if (params.preload) {
webPreferences.preloadURL = params.preload;
}
// Security options that guest will always inherit from embedder
const inheritedWebPreferences = new Map([
['contextIsolation', true],
['javascript', false],
['nodeIntegration', false],
['sandbox', true],
['nodeIntegrationInSubFrames', false],
['enableWebSQL', false]
]);
// Inherit certain option values from embedder
const lastWebPreferences = embedder.getLastWebPreferences()!;
for (const [name, value] of inheritedWebPreferences) {
if (lastWebPreferences[name as keyof Electron.WebPreferences] === value) {
(webPreferences as any)[name] = value;
}
}
return webPreferences;
}
function makeLoadURLOptions (params: Record<string, any>) {
const opts: Electron.LoadURLOptions = {};
if (params.httpreferrer) {
opts.httpReferrer = params.httpreferrer;
}
if (params.useragent) {
opts.userAgent = params.useragent;
}
return opts;
}
2016-01-14 18:35:29 +00:00
// Create a new guest instance.
const createGuest = function (embedder: Electron.WebContents, embedderFrameId: number, elementInstanceId: number, params: Record<string, any>) {
// eslint-disable-next-line no-undef
const guest = (webContents as typeof ElectronInternal.WebContents).create({
type: 'webview',
partition: params.partition,
embedder
2020-03-20 20:28:31 +00:00
});
const guestInstanceId = guest.id;
guestInstances.set(guestInstanceId, {
guest,
embedder
});
2016-01-12 02:40:23 +00:00
// Clear the guest from map when it is destroyed.
guest.once('destroyed', () => {
if (guestInstances.has(guestInstanceId)) {
2020-03-20 20:28:31 +00:00
detachGuest(embedder, guestInstanceId);
}
2020-03-20 20:28:31 +00:00
});
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' as any, function (this: Electron.WebContents, event: Electron.Event) {
const params = this.attachParams!;
delete this.attachParams;
2020-03-20 20:28:31 +00:00
const previouslyAttached = this.viewInstanceId != null;
this.viewInstanceId = params.instanceId;
// Only load URL and set size on first attach
if (previouslyAttached) {
2020-03-20 20:28:31 +00:00
return;
}
2016-01-12 02:40:23 +00:00
if (params.src) {
this.loadURL(params.src, params.opts);
2016-01-12 02:40:23 +00:00
}
2020-03-20 20:28:31 +00:00
embedder.emit('did-attach-webview', event, guest);
});
2016-01-12 02:40:23 +00:00
const sendToEmbedder = (channel: string, ...args: any[]) => {
if (!embedder.isDestroyed()) {
2020-03-20 20:28:31 +00:00
embedder._sendInternal(`${channel}-${guest.viewInstanceId}`, ...args);
2016-11-03 17:39:40 +00:00
}
2020-03-20 20:28:31 +00:00
};
2016-11-03 17:39:40 +00:00
const makeProps = (eventKey: string, args: any[]) => {
const props: Record<string, any> = {};
webViewEvents[eventKey].forEach((prop, index) => {
props[prop] = args[index];
2020-03-20 20:28:31 +00:00
});
return props;
2020-03-20 20:28:31 +00:00
};
// Dispatch events to embedder.
2016-06-07 17:24:48 +00:00
for (const event of supportedWebViewEvents) {
guest.on(event as any, function (_, ...args: any[]) {
sendToEmbedder(IPC_MESSAGES.GUEST_VIEW_INTERNAL_DISPATCH_EVENT, event, makeProps(event, args));
});
2016-01-12 02:40:23 +00:00
}
guest.on('new-window', function (event, url, frameName, disposition, options) {
sendToEmbedder(IPC_MESSAGES.GUEST_VIEW_INTERNAL_DISPATCH_EVENT, 'new-window', {
url,
frameName,
disposition,
options: sanitizeOptionsForGuest(options)
});
2020-03-20 20:28:31 +00:00
});
refactor: use v8 serialization for ipc (#20214) * refactor: use v8 serialization for ipc * cloning process.env doesn't work * serialize host objects by enumerating key/values * new serialization can handle NaN, Infinity, and undefined correctly * can't allocate v8 objects during GC * backport microtasks fix * fix compile * fix node_stream_loader reentrancy * update subframe spec to expect undefined instead of null * write undefined instead of crashing when serializing host objects * fix webview spec * fix download spec * buffers are transformed into uint8arrays * can't serialize promises * fix chrome.i18n.getMessage * fix devtools tests * fix zoom test * fix debug build * fix lint * update ipcRenderer tests * fix printToPDF test * update patch * remove accidentally re-added remote-side spec * wip * don't attempt to serialize host objects * jump through different hoops to set options.webContents sometimes * whoops * fix lint * clean up error-handling logic * fix memory leak * fix lint * convert host objects using old base::Value serialization * fix lint more * fall back to base::Value-based serialization * remove commented-out code * add docs to breaking-changes.md * Update breaking-changes.md * update ipcRenderer and WebContents docs * lint * use named values for format tag * save a memcpy for ~30% speedup * get rid of calls to ShallowClone * extra debugging for paranoia * d'oh, use the correct named tags * apparently msstl doesn't like this DCHECK * funny story about that DCHECK * disable remote-related functions when enable_remote_module = false * nits * use EnableIf to disable remote methods in mojom * fix include * review comments
2019-10-09 17:59:08 +00:00
2016-01-14 18:35:29 +00:00
// Dispatch guest's IPC messages to embedder.
guest.on('ipc-message-host' as any, function (event: Electron.IpcMainEvent, channel: string, args: any[]) {
sendToEmbedder(IPC_MESSAGES.GUEST_VIEW_INTERNAL_DISPATCH_EVENT, 'ipc-message', {
frameId: [event.processId, event.frameId],
channel,
args
});
2020-03-20 20:28:31 +00:00
});
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.get(guestInstanceId);
if (guestInstance != null && guestInstance.visibilityState != null) {
guest._sendInternal(IPC_MESSAGES.GUEST_INSTANCE_VISIBILITY_CHANGE, guestInstance.visibilityState);
}
2020-03-20 20:28:31 +00:00
});
if (attachGuest(embedder, embedderFrameId, elementInstanceId, guestInstanceId, params)) {
return guestInstanceId;
}
return -1;
};
// Attach the guest to an element of embedder.
const attachGuest = function (embedder: Electron.WebContents, embedderFrameId: number, elementInstanceId: number, guestInstanceId: number, params: Record<string, any>) {
2016-01-14 18:35:29 +00:00
// Destroy the old guest when attaching.
2020-03-20 20:28:31 +00:00
const key = `${embedder.id}-${elementInstanceId}`;
const oldGuestInstanceId = embedderElementsMap.get(key);
2016-01-12 02:40:23 +00:00
if (oldGuestInstanceId != null) {
// Reattachment to the same guest is just a no-op.
if (oldGuestInstanceId === guestInstanceId) {
return false;
}
const oldGuestInstance = guestInstances.get(oldGuestInstanceId);
if (oldGuestInstance) {
2020-03-20 20:28:31 +00:00
oldGuestInstance.guest.detachFromOuterFrame();
}
2016-01-12 02:40:23 +00:00
}
const guestInstance = guestInstances.get(guestInstanceId);
// If this isn't a valid guest instance then do nothing.
if (!guestInstance) {
console.error(new Error(`Guest attach failed: Invalid guestInstanceId ${guestInstanceId}`));
return false;
}
const { guest } = guestInstance;
if (guest.hostWebContents !== embedder) {
console.error(new Error(`Guest attach failed: Access denied to guestInstanceId ${guestInstanceId}`));
return false;
}
const { instanceId } = params;
// If this guest is already attached to an element then remove it
if (guestInstance.elementInstanceId) {
const oldKey = `${guestInstance.embedder.id}-${guestInstance.elementInstanceId}`;
embedderElementsMap.delete(oldKey);
// Remove guest from embedder if moving across web views
if (guest.viewInstanceId !== instanceId) {
webViewManager.removeGuest(guestInstance.embedder, guestInstanceId);
guestInstance.embedder._sendInternal(`${IPC_MESSAGES.GUEST_VIEW_INTERNAL_DESTROY_GUEST}-${guest.viewInstanceId}`);
}
}
const webPreferences = makeWebPreferences(embedder, params);
const event = eventBinding.createWithSender(embedder);
embedder.emit('will-attach-webview', event, webPreferences, params);
if (event.defaultPrevented) {
if (guest.viewInstanceId == null) guest.viewInstanceId = instanceId;
guest.destroy();
return false;
}
guest.attachParams = { instanceId, src: params.src, opts: makeLoadURLOptions(params) };
embedderElementsMap.set(key, guestInstanceId);
2020-03-20 20:28:31 +00:00
guest.setEmbedder(embedder);
guestInstance.embedder = embedder;
guestInstance.elementInstanceId = elementInstanceId;
2020-03-20 20:28:31 +00:00
watchEmbedder(embedder);
2016-01-12 02:40:23 +00:00
webViewManager.addGuest(guestInstanceId, embedder, guest, webPreferences);
2020-03-20 20:28:31 +00:00
guest.attachToIframe(embedder, embedderFrameId);
return true;
2020-03-20 20:28:31 +00:00
};
// Remove an guest-embedder relationship.
const detachGuest = function (embedder: Electron.WebContents, guestInstanceId: number) {
const guestInstance = guestInstances.get(guestInstanceId);
if (!guestInstance) return;
if (embedder !== guestInstance.embedder) {
2020-03-20 20:28:31 +00:00
return;
}
2020-03-20 20:28:31 +00:00
webViewManager.removeGuest(embedder, guestInstanceId);
guestInstances.delete(guestInstanceId);
2020-03-20 20:28:31 +00:00
const key = `${embedder.id}-${guestInstance.elementInstanceId}`;
embedderElementsMap.delete(key);
2020-03-20 20:28:31 +00:00
};
// Once an embedder has had a guest attached we watch it for destruction to
// destroy any remaining guests.
const watchedEmbedders = new Set<Electron.WebContents>();
const watchEmbedder = function (embedder: Electron.WebContents) {
if (watchedEmbedders.has(embedder)) {
2020-03-20 20:28:31 +00:00
return;
}
2020-03-20 20:28:31 +00:00
watchedEmbedders.add(embedder);
// Forward embedder window visibility change events to guest
const onVisibilityChange = function (visibilityState: VisibilityState) {
for (const guestInstance of guestInstances.values()) {
2020-03-20 20:28:31 +00:00
guestInstance.visibilityState = visibilityState;
if (guestInstance.embedder === embedder) {
guestInstance.guest._sendInternal(IPC_MESSAGES.GUEST_INSTANCE_VISIBILITY_CHANGE, visibilityState);
}
}
2020-03-20 20:28:31 +00:00
};
embedder.on('-window-visibility-change' as any, onVisibilityChange);
embedder.once('will-destroy' as any, () => {
// 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, guestInstance] of guestInstances) {
if (guestInstance.embedder === embedder) {
detachGuest(embedder, guestInstanceId);
}
}
// Clear the listeners.
embedder.removeListener('-window-visibility-change' as any, onVisibilityChange);
2020-03-20 20:28:31 +00:00
watchedEmbedders.delete(embedder);
});
};
2016-01-12 02:40:23 +00:00
2020-03-20 20:28:31 +00:00
const isWebViewTagEnabledCache = new WeakMap();
const isWebViewTagEnabled = function (contents: Electron.WebContents) {
if (!isWebViewTagEnabledCache.has(contents)) {
2020-03-20 20:28:31 +00:00
const webPreferences = contents.getLastWebPreferences() || {};
isWebViewTagEnabledCache.set(contents, !!webPreferences.webviewTag);
}
2020-03-20 20:28:31 +00:00
return isWebViewTagEnabledCache.get(contents);
};
const makeSafeHandler = function<Event extends { sender: Electron.WebContents }> (channel: string, handler: (event: Event, ...args: any[]) => any) {
return (event: Event, ...args: any[]) => {
if (isWebViewTagEnabled(event.sender)) {
2020-03-20 20:28:31 +00:00
return handler(event, ...args);
} else {
2020-03-20 20:28:31 +00:00
console.error(`<webview> IPC message ${channel} sent by WebContents with <webview> disabled (${event.sender.id})`);
throw new Error('<webview> disabled');
}
2020-03-20 20:28:31 +00:00
};
};
const handleMessage = function (channel: string, handler: (event: Electron.IpcMainInvokeEvent, ...args: any[]) => any) {
2020-03-20 20:28:31 +00:00
ipcMainInternal.handle(channel, makeSafeHandler(channel, handler));
};
const handleMessageSync = function (channel: string, handler: (event: ElectronInternal.IpcMainInternalEvent, ...args: any[]) => any) {
2020-03-20 20:28:31 +00:00
ipcMainUtils.handleSync(channel, makeSafeHandler(channel, handler));
};
handleMessage(IPC_MESSAGES.GUEST_VIEW_MANAGER_CREATE_AND_ATTACH_GUEST, function (event, embedderFrameId: number, elementInstanceId: number, params) {
return createGuest(event.sender, embedderFrameId, elementInstanceId, params);
2020-03-20 20:28:31 +00:00
});
2016-01-12 02:40:23 +00:00
handleMessageSync(IPC_MESSAGES.GUEST_VIEW_MANAGER_DETACH_GUEST, function (event, guestInstanceId: number) {
return detachGuest(event.sender, guestInstanceId);
});
// this message is sent by the actual <webview>
ipcMainInternal.on(IPC_MESSAGES.GUEST_VIEW_MANAGER_FOCUS_CHANGE, function (event: ElectronInternal.IpcMainInternalEvent, focus: boolean) {
event.sender.emit('-focus-change', {}, focus);
2020-03-20 20:28:31 +00:00
});
handleMessage(IPC_MESSAGES.GUEST_VIEW_MANAGER_CALL, function (event, guestInstanceId: number, method: string, args: any[]) {
2020-03-20 20:28:31 +00:00
const guest = getGuestForWebContents(guestInstanceId, event.sender);
if (!asyncMethods.has(method)) {
2020-03-20 20:28:31 +00:00
throw new Error(`Invalid method: ${method}`);
}
return (guest as any)[method](...args);
2020-03-20 20:28:31 +00:00
});
handleMessageSync(IPC_MESSAGES.GUEST_VIEW_MANAGER_CALL, function (event, guestInstanceId: number, method: string, args: any[]) {
2020-03-20 20:28:31 +00:00
const guest = getGuestForWebContents(guestInstanceId, event.sender);
if (!syncMethods.has(method)) {
2020-03-20 20:28:31 +00:00
throw new Error(`Invalid method: ${method}`);
}
return (guest as any)[method](...args);
2020-03-20 20:28:31 +00:00
});
handleMessageSync(IPC_MESSAGES.GUEST_VIEW_MANAGER_PROPERTY_GET, function (event, guestInstanceId: number, property: string) {
2020-03-20 20:28:31 +00:00
const guest = getGuestForWebContents(guestInstanceId, event.sender);
if (!properties.has(property)) {
2020-03-20 20:28:31 +00:00
throw new Error(`Invalid property: ${property}`);
}
return (guest as any)[property];
2020-03-20 20:28:31 +00:00
});
handleMessageSync(IPC_MESSAGES.GUEST_VIEW_MANAGER_PROPERTY_SET, function (event, guestInstanceId: number, property: string, val: any) {
2020-03-20 20:28:31 +00:00
const guest = getGuestForWebContents(guestInstanceId, event.sender);
if (!properties.has(property)) {
2020-03-20 20:28:31 +00:00
throw new Error(`Invalid property: ${property}`);
}
(guest as any)[property] = val;
2020-03-20 20:28:31 +00:00
});
// Returns WebContents from its guest id hosted in given webContents.
const getGuestForWebContents = function (guestInstanceId: number, contents: Electron.WebContents) {
const guestInstance = guestInstances.get(guestInstanceId);
if (!guestInstance) {
2020-03-20 20:28:31 +00:00
throw new Error(`Invalid guestInstanceId: ${guestInstanceId}`);
}
if (guestInstance.guest.hostWebContents !== contents) {
2020-03-20 20:28:31 +00:00
throw new Error(`Access denied to guestInstanceId: ${guestInstanceId}`);
}
return guestInstance.guest;
2020-03-20 20:28:31 +00:00
};