Clean up the Chrome API implementation code

This commit is contained in:
Cheng Zhao 2016-05-28 17:51:49 +09:00
parent 31628abadc
commit d55b96fdf5
3 changed files with 54 additions and 50 deletions

View file

@ -12,26 +12,26 @@ const matchesPattern = function (pattern) {
// Run the code with chrome API integrated.
const runContentScript = function (extensionId, url, code) {
const chrome = {}
require('./chrome-api').injectTo(extensionId, chrome)
const context = {}
require('./chrome-api').injectTo(extensionId, context)
const wrapper = `(function (chrome) {\n ${code}\n })`
const compiledWrapper = runInThisContext(wrapper, {
filename: url,
lineOffset: 1,
displayErrors: true
})
return compiledWrapper.call(this, chrome)
return compiledWrapper.call(this, context.chrome)
}
// Run injected scripts.
// https://developer.chrome.com/extensions/content_scripts
const injectContentScript = function (script) {
const injectContentScript = function (extensionId, script) {
for (const match of script.matches) {
if (!matchesPattern(match)) return
}
for (const {url, code} of script.js) {
const fire = runContentScript.bind(window, script.extensionId, url, code)
const fire = runContentScript.bind(window, extensionId, url, code)
if (script.runAt === 'document_start') {
process.once('document-start', fire)
} else if (script.runAt === 'document_end') {
@ -53,7 +53,9 @@ const preferences = process.getRenderProcessPreferences()
if (preferences) {
for (const pref of preferences) {
if (pref.contentScripts) {
pref.contentScripts.forEach(injectContentScript)
for (const script of pref.contentScripts) {
injectContentScript(pref.extensionId, script)
}
}
}
}