refactor: use ipcMainUtils.invokeInWebContents / ipcRendererUtils.handle helpers for Chrome APIs (#17417)

This commit is contained in:
Milan Burda 2019-03-26 03:38:35 +01:00 committed by Cheng Zhao
parent 546466b209
commit 336db33d18
9 changed files with 82 additions and 99 deletions

View file

@ -180,12 +180,12 @@ const webFrameMethods = [
for (const method of webFrameMethods) { for (const method of webFrameMethods) {
WebContents.prototype[method] = function (...args) { WebContents.prototype[method] = function (...args) {
ipcMainUtils.invokeInWebContents(this, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, ...args) ipcMainUtils.invokeInWebContents(this, false, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, ...args)
} }
} }
const executeJavaScript = (contents, code, hasUserGesture) => { const executeJavaScript = (contents, code, hasUserGesture) => {
return ipcMainUtils.invokeInWebContents(contents, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', 'executeJavaScript', code, hasUserGesture) return ipcMainUtils.invokeInWebContents(contents, false, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', 'executeJavaScript', code, hasUserGesture)
} }
// Make sure WebContents::executeJavaScript would run the code only when the // Make sure WebContents::executeJavaScript would run the code only when the

View file

@ -3,7 +3,6 @@
const { app, webContents, BrowserWindow } = require('electron') const { app, webContents, BrowserWindow } = require('electron')
const { getAllWebContents } = process.electronBinding('web_contents') const { getAllWebContents } = process.electronBinding('web_contents')
const renderProcessPreferences = process.electronBinding('render_process_preferences').forAllWebContents() const renderProcessPreferences = process.electronBinding('render_process_preferences').forAllWebContents()
const { ipcMainInternal } = require('@electron/internal/browser/ipc-main-internal')
const ipcMainUtils = require('@electron/internal/browser/ipc-main-internal-utils') const ipcMainUtils = require('@electron/internal/browser/ipc-main-internal-utils')
const { Buffer } = require('buffer') const { Buffer } = require('buffer')
@ -29,6 +28,10 @@ const isWindowOrWebView = function (webContents) {
return type === 'window' || type === 'webview' return type === 'window' || type === 'webview'
} }
const isBackgroundPage = function (webContents) {
return webContents.getType() === 'backgroundPage'
}
// Create or get manifest object from |srcDirectory|. // Create or get manifest object from |srcDirectory|.
const getManifestFromPath = function (srcDirectory) { const getManifestFromPath = function (srcDirectory) {
let manifest let manifest
@ -94,7 +97,6 @@ const startBackgroundPages = function (manifest) {
const contents = webContents.create({ const contents = webContents.create({
partition: 'persist:__chrome_extension', partition: 'persist:__chrome_extension',
isBackgroundPage: true, isBackgroundPage: true,
commandLineSwitches: ['--background-page'],
sandbox: true, sandbox: true,
enableRemoteModule: false enableRemoteModule: false
}) })
@ -156,21 +158,26 @@ const hookWebContentsEvents = function (webContents) {
// Handle the chrome.* API messages. // Handle the chrome.* API messages.
let nextId = 0 let nextId = 0
ipcMainInternal.on('CHROME_RUNTIME_CONNECT', function (event, extensionId, connectInfo) { ipcMainUtils.handle('CHROME_RUNTIME_CONNECT', function (event, extensionId, connectInfo) {
const page = backgroundPages[extensionId] if (isBackgroundPage(event.sender)) {
if (!page) { throw new Error('chrome.runtime.connect is not supported in background page')
console.error(`Connect to unknown extension ${extensionId}`)
return
} }
const page = backgroundPages[extensionId]
if (!page) {
throw new Error(`Connect to unknown extension ${extensionId}`)
}
const tabId = page.webContents.id
const portId = ++nextId const portId = ++nextId
event.returnValue = { tabId: page.webContents.id, portId: portId }
event.sender.once('render-view-deleted', () => { event.sender.once('render-view-deleted', () => {
if (page.webContents.isDestroyed()) return if (page.webContents.isDestroyed()) return
page.webContents._sendInternalToAll(`CHROME_PORT_DISCONNECT_${portId}`) page.webContents._sendInternalToAll(`CHROME_PORT_DISCONNECT_${portId}`)
}) })
page.webContents._sendInternalToAll(`CHROME_RUNTIME_ONCONNECT_${extensionId}`, event.sender.id, portId, connectInfo) page.webContents._sendInternalToAll(`CHROME_RUNTIME_ONCONNECT_${extensionId}`, event.sender.id, portId, connectInfo)
return { tabId, portId }
}) })
ipcMainUtils.handle('CHROME_EXTENSION_MANIFEST', function (event, extensionId) { ipcMainUtils.handle('CHROME_EXTENSION_MANIFEST', function (event, extensionId) {
@ -181,35 +188,28 @@ ipcMainUtils.handle('CHROME_EXTENSION_MANIFEST', function (event, extensionId) {
return manifest return manifest
}) })
let resultID = 1 ipcMainUtils.handle('CHROME_RUNTIME_SEND_MESSAGE', async function (event, extensionId, message) {
ipcMainInternal.on('CHROME_RUNTIME_SENDMESSAGE', function (event, extensionId, message, originResultID) { if (isBackgroundPage(event.sender)) {
throw new Error('chrome.runtime.sendMessage is not supported in background page')
}
const page = backgroundPages[extensionId] const page = backgroundPages[extensionId]
if (!page) { if (!page) {
console.error(`Connect to unknown extension ${extensionId}`) throw new Error(`Connect to unknown extension ${extensionId}`)
return
} }
page.webContents._sendInternalToAll(`CHROME_RUNTIME_ONMESSAGE_${extensionId}`, event.sender.id, message, resultID) return ipcMainUtils.invokeInWebContents(page.webContents, true, `CHROME_RUNTIME_ONMESSAGE_${extensionId}`, event.sender.id, message)
ipcMainInternal.once(`CHROME_RUNTIME_ONMESSAGE_RESULT_${resultID}`, (resultEvent, result) => {
event._replyInternal(`CHROME_RUNTIME_SENDMESSAGE_RESULT_${originResultID}`, result)
})
resultID++
}) })
ipcMainInternal.on('CHROME_TABS_SEND_MESSAGE', function (event, tabId, extensionId, isBackgroundPage, message, originResultID) { ipcMainUtils.handle('CHROME_TABS_SEND_MESSAGE', async function (event, tabId, extensionId, message) {
const contents = webContents.fromId(tabId) const contents = webContents.fromId(tabId)
if (!contents) { if (!contents) {
console.error(`Sending message to unknown tab ${tabId}`) throw new Error(`Sending message to unknown tab ${tabId}`)
return
} }
const senderTabId = isBackgroundPage ? null : event.sender.id const senderTabId = isBackgroundPage(event.sender) ? null : event.sender.id
contents._sendInternalToAll(`CHROME_RUNTIME_ONMESSAGE_${extensionId}`, senderTabId, message, resultID) return ipcMainUtils.invokeInWebContents(contents, true, `CHROME_RUNTIME_ONMESSAGE_${extensionId}`, senderTabId, message)
ipcMainInternal.once(`CHROME_RUNTIME_ONMESSAGE_RESULT_${resultID}`, (resultEvent, result) => {
event._replyInternal(`CHROME_TABS_SEND_MESSAGE_RESULT_${originResultID}`, result)
})
resultID++
}) })
const getLanguage = () => { const getLanguage = () => {
@ -301,17 +301,20 @@ const isChromeExtension = function (pageURL) {
return protocol === 'chrome-extension:' return protocol === 'chrome-extension:'
} }
ipcMainInternal.on('CHROME_TABS_EXECUTESCRIPT', function (event, requestId, tabId, extensionId, details) { const assertChromeExtension = function (contents, api) {
const pageURL = event.sender._getURL() const pageURL = contents._getURL()
if (!isChromeExtension(pageURL)) { if (!isChromeExtension(pageURL)) {
console.error(`Blocked ${pageURL} from calling chrome.tabs.executeScript()`) console.error(`Blocked ${pageURL} from calling ${api}`)
return throw new Error(`Blocked ${api}`)
} }
}
ipcMainUtils.handle('CHROME_TABS_EXECUTE_SCRIPT', async function (event, tabId, extensionId, details) {
assertChromeExtension(event.sender, 'chrome.tabs.executeScript()')
const contents = webContents.fromId(tabId) const contents = webContents.fromId(tabId)
if (!contents) { if (!contents) {
console.error(`Sending message to unknown tab ${tabId}`) throw new Error(`Sending message to unknown tab ${tabId}`)
return
} }
let code, url let code, url
@ -324,7 +327,7 @@ ipcMainInternal.on('CHROME_TABS_EXECUTESCRIPT', function (event, requestId, tabI
url = `chrome-extension://${extensionId}/${String(Math.random()).substr(2, 8)}.js` url = `chrome-extension://${extensionId}/${String(Math.random()).substr(2, 8)}.js`
} }
contents._sendInternal('CHROME_TABS_EXECUTESCRIPT', event.sender.id, requestId, extensionId, url, code) return ipcMainUtils.invokeInWebContents(contents, false, 'CHROME_TABS_EXECUTE_SCRIPT', extensionId, url, code)
}) })
// Transfer the content scripts to renderer. // Transfer the content scripts to renderer.

View file

@ -26,7 +26,7 @@ export const handle = function <T extends IPCHandler> (channel: string, handler:
let nextId = 0 let nextId = 0
export function invokeInWebContents<T> (sender: Electron.WebContentsInternal, command: string, ...args: any[]) { export function invokeInWebContents<T> (sender: Electron.WebContentsInternal, sendToAll: boolean, command: string, ...args: any[]) {
return new Promise<T>((resolve, reject) => { return new Promise<T>((resolve, reject) => {
const requestId = ++nextId const requestId = ++nextId
const channel = `${command}_RESPONSE_${requestId}` const channel = `${command}_RESPONSE_${requestId}`
@ -46,6 +46,11 @@ export function invokeInWebContents<T> (sender: Electron.WebContentsInternal, co
resolve(result) resolve(result)
} }
}) })
if (sendToAll) {
sender._sendInternalToAll(command, requestId, ...args)
} else {
sender._sendInternal(command, requestId, ...args) sender._sendInternal(command, requestId, ...args)
}
}) })
} }

View file

@ -33,5 +33,5 @@ const extensionId = v8Util.getHiddenValue(isolatedWorld, `extension-${worldId}`)
if (extensionId) { if (extensionId) {
const chromeAPI = require('@electron/internal/renderer/chrome-api') const chromeAPI = require('@electron/internal/renderer/chrome-api')
chromeAPI.injectTo(extensionId, false, window) chromeAPI.injectTo(extensionId, window)
} }

View file

@ -67,22 +67,20 @@ class Port {
} }
// Inject chrome API to the |context| // Inject chrome API to the |context|
export function injectTo (extensionId: string, isBackgroundPage: boolean, context: any) { export function injectTo (extensionId: string, context: any) {
const chrome = context.chrome = context.chrome || {} const chrome = context.chrome = context.chrome || {}
let originResultID = 1
ipcRendererInternal.on(`CHROME_RUNTIME_ONCONNECT_${extensionId}`, ( ipcRendererInternal.on(`CHROME_RUNTIME_ONCONNECT_${extensionId}`, (
_event: Electron.Event, tabId: number, portId: number, connectInfo: { name: string } _event: Electron.Event, tabId: number, portId: number, connectInfo: { name: string }
) => { ) => {
chrome.runtime.onConnect.emit(new Port(tabId, portId, extensionId, connectInfo.name)) chrome.runtime.onConnect.emit(new Port(tabId, portId, extensionId, connectInfo.name))
} })
)
ipcRendererInternal.on(`CHROME_RUNTIME_ONMESSAGE_${extensionId}`, ( ipcRendererUtils.handle(`CHROME_RUNTIME_ONMESSAGE_${extensionId}`, (
_event: Electron.Event, tabId: number, message: string, resultID: number _event: Electron.Event, tabId: number, message: string
) => { ) => {
chrome.runtime.onMessage.emit(message, new MessageSender(tabId, extensionId), (messageResult: any) => { return new Promise(resolve => {
ipcRendererInternal.send(`CHROME_RUNTIME_ONMESSAGE_RESULT_${resultID}`, messageResult) chrome.runtime.onMessage.emit(message, new MessageSender(tabId, extensionId), resolve)
}) })
}) })
@ -115,11 +113,6 @@ export function injectTo (extensionId: string, isBackgroundPage: boolean, contex
// https://developer.chrome.com/extensions/runtime#method-connect // https://developer.chrome.com/extensions/runtime#method-connect
connect (...args: Array<any>) { connect (...args: Array<any>) {
if (isBackgroundPage) {
console.error('chrome.runtime.connect is not supported in background page')
return
}
// Parse the optional args. // Parse the optional args.
let targetExtensionId = extensionId let targetExtensionId = extensionId
let connectInfo = { name: '' } let connectInfo = { name: '' }
@ -135,36 +128,33 @@ export function injectTo (extensionId: string, isBackgroundPage: boolean, contex
// https://developer.chrome.com/extensions/runtime#method-sendMessage // https://developer.chrome.com/extensions/runtime#method-sendMessage
sendMessage (...args: Array<any>) { sendMessage (...args: Array<any>) {
if (isBackgroundPage) {
console.error('chrome.runtime.sendMessage is not supported in background page')
return
}
// Parse the optional args. // Parse the optional args.
let targetExtensionId = extensionId const targetExtensionId = extensionId
let message let message: string
let options: Object | undefined
let responseCallback: Chrome.Tabs.SendMessageCallback = () => {}
if (typeof args[args.length - 1] === 'function') {
responseCallback = args.pop()
}
if (args.length === 1) { if (args.length === 1) {
message = args[0] [message] = args
} else if (args.length === 2) { } else if (args.length === 2) {
// A case of not provide extension-id: (message, responseCallback) if (typeof args[0] === 'string') {
if (typeof args[1] === 'function') { [extensionId, message] = args
ipcRendererInternal.once(`CHROME_RUNTIME_SENDMESSAGE_RESULT_${originResultID}`,
(_event: Electron.Event, result: any) => args[1](result)
)
message = args[0]
} else { } else {
[targetExtensionId, message] = args [message, options] = args
} }
} else { } else {
console.error('options is not supported') [extensionId, message, options] = args
ipcRendererInternal.once(`CHROME_RUNTIME_SENDMESSAGE_RESULT_${originResultID}`,
(event: Electron.Event, result: any) => args[2](result)
)
} }
ipcRendererInternal.send('CHROME_RUNTIME_SENDMESSAGE', targetExtensionId, message, originResultID) if (options) {
originResultID++ console.error('options are not supported')
}
ipcRendererUtils.invoke('CHROME_RUNTIME_SEND_MESSAGE', targetExtensionId, message).then(responseCallback)
}, },
onConnect: new Event(), onConnect: new Event(),
@ -177,15 +167,10 @@ export function injectTo (extensionId: string, isBackgroundPage: boolean, contex
executeScript ( executeScript (
tabId: number, tabId: number,
details: Chrome.Tabs.ExecuteScriptDetails, details: Chrome.Tabs.ExecuteScriptDetails,
resultCallback: Chrome.Tabs.ExecuteScriptCallback resultCallback: Chrome.Tabs.ExecuteScriptCallback = () => {}
) { ) {
if (resultCallback) { ipcRendererUtils.invoke('CHROME_TABS_EXECUTE_SCRIPT', tabId, extensionId, details)
ipcRendererInternal.once(`CHROME_TABS_EXECUTESCRIPT_RESULT_${originResultID}`, .then((result: any) => resultCallback([result]))
(_event: Electron.Event, result: any) => resultCallback([result])
)
}
ipcRendererInternal.send('CHROME_TABS_EXECUTESCRIPT', originResultID, tabId, extensionId, details)
originResultID++
}, },
// https://developer.chrome.com/extensions/tabs#method-sendMessage // https://developer.chrome.com/extensions/tabs#method-sendMessage
@ -193,15 +178,9 @@ export function injectTo (extensionId: string, isBackgroundPage: boolean, contex
tabId: number, tabId: number,
message: any, message: any,
_options: Chrome.Tabs.SendMessageDetails, _options: Chrome.Tabs.SendMessageDetails,
responseCallback: Chrome.Tabs.SendMessageCallback responseCallback: Chrome.Tabs.SendMessageCallback = () => {}
) { ) {
if (responseCallback) { ipcRendererUtils.invoke('CHROME_TABS_SEND_MESSAGE', tabId, extensionId, message).then(responseCallback)
ipcRendererInternal.once(`CHROME_TABS_SEND_MESSAGE_RESULT_${originResultID}`,
(_event: Electron.Event, result: any) => responseCallback(result)
)
}
ipcRendererInternal.send('CHROME_TABS_SEND_MESSAGE', tabId, extensionId, isBackgroundPage, message, originResultID)
originResultID++
}, },
onUpdated: new Event(), onUpdated: new Event(),

View file

@ -1,6 +1,7 @@
import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal'
import { webFrame } from 'electron' import { webFrame } from 'electron'
import * as ipcRendererUtils from '@electron/internal/renderer/ipc-renderer-internal-utils'
const v8Util = process.electronBinding('v8_util') const v8Util = process.electronBinding('v8_util')
const IsolatedWorldIDs = { const IsolatedWorldIDs = {
@ -94,17 +95,13 @@ const injectContentScript = function (extensionId: string, script: Electron.Cont
} }
// Handle the request of chrome.tabs.executeJavaScript. // Handle the request of chrome.tabs.executeJavaScript.
ipcRendererInternal.on('CHROME_TABS_EXECUTESCRIPT', function ( ipcRendererUtils.handle('CHROME_TABS_EXECUTE_SCRIPT', function (
event: Electron.Event, event: Electron.Event,
senderWebContentsId: number,
requestId: number,
extensionId: string, extensionId: string,
url: string, url: string,
code: string code: string
) { ) {
runContentScript.call(window, extensionId, url, code).then(result => { return runContentScript.call(window, extensionId, url, code)
ipcRendererInternal.sendToAll(senderWebContentsId, `CHROME_TABS_EXECUTESCRIPT_RESULT_${requestId}`, result)
})
}) })
module.exports = (getRenderProcessPreferences: typeof process.getRenderProcessPreferences) => { module.exports = (getRenderProcessPreferences: typeof process.getRenderProcessPreferences) => {

View file

@ -49,7 +49,6 @@ const contextIsolation = hasSwitch('context-isolation')
const nodeIntegration = hasSwitch('node-integration') const nodeIntegration = hasSwitch('node-integration')
const webviewTag = hasSwitch('webview-tag') const webviewTag = hasSwitch('webview-tag')
const isHiddenPage = hasSwitch('hidden-page') const isHiddenPage = hasSwitch('hidden-page')
const isBackgroundPage = hasSwitch('background-page')
const usesNativeWindowOpen = hasSwitch('native-window-open') const usesNativeWindowOpen = hasSwitch('native-window-open')
const preloadScript = parseOption('preload', null) const preloadScript = parseOption('preload', null)
@ -74,7 +73,7 @@ switch (window.location.protocol) {
} }
case 'chrome-extension:': { case 'chrome-extension:': {
// Inject the chrome.* APIs that chrome extensions require // Inject the chrome.* APIs that chrome extensions require
require('@electron/internal/renderer/chrome-api').injectTo(window.location.hostname, isBackgroundPage, window) require('@electron/internal/renderer/chrome-api').injectTo(window.location.hostname, window)
break break
} }
case 'chrome:': case 'chrome:':

View file

@ -105,7 +105,6 @@ function preloadRequire (module) {
// Process command line arguments. // Process command line arguments.
const { hasSwitch } = process.electronBinding('command_line') const { hasSwitch } = process.electronBinding('command_line')
const isBackgroundPage = hasSwitch('background-page')
const contextIsolation = hasSwitch('context-isolation') const contextIsolation = hasSwitch('context-isolation')
switch (window.location.protocol) { switch (window.location.protocol) {
@ -116,7 +115,7 @@ switch (window.location.protocol) {
} }
case 'chrome-extension:': { case 'chrome-extension:': {
// Inject the chrome.* APIs that chrome extensions require // Inject the chrome.* APIs that chrome extensions require
require('@electron/internal/renderer/chrome-api').injectTo(window.location.hostname, isBackgroundPage, window) require('@electron/internal/renderer/chrome-api').injectTo(window.location.hostname, window)
break break
} }
case 'chrome': { case 'chrome': {

View file

@ -61,6 +61,7 @@ declare namespace Electron {
interface WebContentsInternal extends Electron.WebContents { interface WebContentsInternal extends Electron.WebContents {
_sendInternal(channel: string, ...args: any[]): void; _sendInternal(channel: string, ...args: any[]): void;
_sendInternalToAll(channel: string, ...args: any[]): void;
} }
const deprecate: ElectronInternal.DeprecationUtil; const deprecate: ElectronInternal.DeprecationUtil;