content-scripts-injector.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const {ipcRenderer} = require('electron')
  2. const {runInThisContext} = require('vm')
  3. // Check whether pattern matches.
  4. // https://developer.chrome.com/extensions/match_patterns
  5. const matchesPattern = function (pattern) {
  6. if (pattern === '<all_urls>') return true
  7. const regexp = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$')
  8. const url = `${location.protocol}//${location.host}${location.pathname}`
  9. return url.match(regexp)
  10. }
  11. // Run the code with chrome API integrated.
  12. const runContentScript = function (extensionId, url, code) {
  13. const context = {}
  14. require('./chrome-api').injectTo(extensionId, false, context)
  15. const wrapper = `(function (chrome) {\n ${code}\n })`
  16. const compiledWrapper = runInThisContext(wrapper, {
  17. filename: url,
  18. lineOffset: 1,
  19. displayErrors: true
  20. })
  21. return compiledWrapper.call(this, context.chrome)
  22. }
  23. // Run injected scripts.
  24. // https://developer.chrome.com/extensions/content_scripts
  25. const injectContentScript = function (extensionId, script) {
  26. if (!script.matches.some(matchesPattern)) return
  27. for (const {url, code} of script.js) {
  28. const fire = runContentScript.bind(window, extensionId, url, code)
  29. if (script.runAt === 'document_start') {
  30. process.once('document-start', fire)
  31. } else if (script.runAt === 'document_end') {
  32. process.once('document-end', fire)
  33. } else if (script.runAt === 'document_idle') {
  34. document.addEventListener('DOMContentLoaded', fire)
  35. }
  36. }
  37. }
  38. // Handle the request of chrome.tabs.executeJavaScript.
  39. ipcRenderer.on('CHROME_TABS_EXECUTESCRIPT', function (event, senderWebContentsId, requestId, extensionId, url, code) {
  40. const result = runContentScript.call(window, extensionId, url, code)
  41. ipcRenderer.sendToAll(senderWebContentsId, `CHROME_TABS_EXECUTESCRIPT_RESULT_${requestId}`, result)
  42. })
  43. // Read the renderer process preferences.
  44. const preferences = process.getRenderProcessPreferences()
  45. if (preferences) {
  46. for (const pref of preferences) {
  47. if (pref.contentScripts) {
  48. for (const script of pref.contentScripts) {
  49. injectContentScript(pref.extensionId, script)
  50. }
  51. }
  52. }
  53. }