2016-05-28 06:37:44 +00:00
|
|
|
const {runInThisContext} = require('vm')
|
2016-05-27 01:29:57 +00:00
|
|
|
|
|
|
|
// Check whether pattern matches.
|
|
|
|
// https://developer.chrome.com/extensions/match_patterns
|
|
|
|
const matchesPattern = function (pattern) {
|
2016-05-27 02:07:06 +00:00
|
|
|
if (pattern === '<all_urls>') return true
|
2016-05-27 01:29:57 +00:00
|
|
|
|
|
|
|
const regexp = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$')
|
|
|
|
return location.href.match(regexp)
|
|
|
|
}
|
|
|
|
|
2016-05-28 06:37:44 +00:00
|
|
|
// Run the code with chrome API integrated.
|
|
|
|
const runContentScript = function (extensionId, url, code) {
|
|
|
|
const chrome = {}
|
|
|
|
require('./chrome-api').injectTo(extensionId, chrome)
|
|
|
|
const wrapper = `(function (chrome) {\n ${code}\n })`
|
|
|
|
const compiledWrapper = runInThisContext(wrapper, {
|
|
|
|
filename: url,
|
|
|
|
lineOffset: 1,
|
|
|
|
displayErrors: true
|
|
|
|
})
|
|
|
|
compiledWrapper.call(this, chrome)
|
|
|
|
}
|
|
|
|
|
2016-05-27 01:29:57 +00:00
|
|
|
// Run injected scripts.
|
|
|
|
// https://developer.chrome.com/extensions/content_scripts
|
|
|
|
const injectContentScript = function (script) {
|
|
|
|
for (const match of script.matches) {
|
|
|
|
if (!matchesPattern(match)) return
|
|
|
|
}
|
|
|
|
|
2016-05-28 06:37:44 +00:00
|
|
|
for (const {url, code} of script.js) {
|
|
|
|
const fire = runContentScript.bind(window, script.extensionId, url, code)
|
2016-05-27 01:29:57 +00:00
|
|
|
if (script.runAt === 'document_start') {
|
2016-05-27 02:07:06 +00:00
|
|
|
process.once('document-start', fire)
|
|
|
|
} else if (script.runAt === 'document_end') {
|
|
|
|
process.once('document-end', fire)
|
|
|
|
} else if (script.runAt === 'document_idle') {
|
|
|
|
document.addEventListener('DOMContentLoaded', fire)
|
2016-05-27 01:29:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read the renderer process preferences.
|
2016-05-27 02:07:06 +00:00
|
|
|
const preferences = process.getRenderProcessPreferences()
|
|
|
|
if (preferences) {
|
|
|
|
for (const pref of preferences) {
|
|
|
|
if (pref.contentScripts) {
|
|
|
|
pref.contentScripts.forEach(injectContentScript)
|
|
|
|
}
|
2016-05-27 01:29:57 +00:00
|
|
|
}
|
|
|
|
}
|