Implement chrome.tabs.executeScript

This commit is contained in:
Cheng Zhao 2016-05-28 16:41:12 +09:00
parent db94121360
commit 31628abadc
3 changed files with 49 additions and 1 deletions

View file

@ -116,6 +116,35 @@ ipcMain.on('CHROME_PORT_POSTMESSAGE', function (event, webContentsId, portId, me
contents.sendToAll(`CHROME_PORT_ONMESSAGE_${portId}`, message)
})
ipcMain.on('CHROME_TABS_EXECUTESCRIPT', function (event, requestId, webContentsId, hostname, details) {
const contents = webContents.fromId(webContentsId)
if (!contents) {
console.error(`Sending message to unkown webContentsId ${webContentsId}`)
return
}
let code, url
if (details.file) {
code = String(fs.readFileSync(path.join(manifest.srcDirectory, details.file)))
url = `chrome-extension://${hostname}/${details.file}`
} else {
code = details.code
url = `chrome-extension://${hostname}/${String(Math.random()).substr(2, 8)}.js`
}
contents.send('CHROME_TABS_EXECUTESCRIPT', requestId, event.sender.id, hostname, url, code)
})
ipcMain.on(`CHROME_TABS_EXECUTESCRIPT_RESULT`, (event, requestId, webContentsId, result) => {
const contents = webContents.fromId(webContentsId)
if (!contents) {
console.error(`Sending message to unkown webContentsId ${webContentsId}`)
return
}
contents.send(`CHROME_TABS_EXECUTESCRIPT_RESULT_${requestId}`, result)
})
// Transfer the content scripts to renderer.
const contentScripts = {}

View file

@ -1,6 +1,8 @@
const {ipcRenderer} = require('electron')
const url = require('url')
let nextId = 0
class Event {
constructor () {
this.listeners = []
@ -113,6 +115,16 @@ exports.injectTo = function (extensionId, context) {
}
}
chrome.tabs = {
executeScript (tabId, details, callback) {
const requestId = ++nextId
ipcRenderer.once(`CHROME_TABS_EXECUTESCRIPT_RESULT_${requestId}`, (event, result) => {
callback([event.result])
})
ipcRenderer.send('CHROME_TABS_EXECUTESCRIPT', requestId, tabId, extensionId, details)
}
}
chrome.extension = {
getURL: chrome.runtime.getURL
}

View file

@ -1,3 +1,4 @@
const {ipcRenderer} = require('electron')
const {runInThisContext} = require('vm')
// Check whether pattern matches.
@ -19,7 +20,7 @@ const runContentScript = function (extensionId, url, code) {
lineOffset: 1,
displayErrors: true
})
compiledWrapper.call(this, chrome)
return compiledWrapper.call(this, chrome)
}
// Run injected scripts.
@ -41,6 +42,12 @@ const injectContentScript = function (script) {
}
}
// Handle the request of chrome.tabs.executeJavaScript.
ipcRenderer.on('CHROME_TABS_EXECUTESCRIPT', function (event, requestId, senderId, extensionId, url, code) {
const result = runContentScript.call(window, extensionId, url, code)
ipcRenderer.send('CHROME_TABS_EXECUTESCRIPT_RESULT', requestId, senderId, result)
})
// Read the renderer process preferences.
const preferences = process.getRenderProcessPreferences()
if (preferences) {