devtools.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // this script is called when the VueDevtools panel is activated.
  2. import { initDevTools } from 'src/devtools'
  3. import Bridge from 'src/bridge'
  4. initDevTools({
  5. /**
  6. * Inject backend, connect to background, and send back the bridge.
  7. *
  8. * @param {Function} cb
  9. */
  10. connect (cb) {
  11. // 1. inject backend code into page
  12. injectScript(chrome.runtime.getURL('build/backend.js'), () => {
  13. // 2. connect to background to setup proxy
  14. const port = chrome.runtime.connect({
  15. name: '' + chrome.devtools.inspectedWindow.tabId
  16. })
  17. let disconnected = false
  18. port.onDisconnect.addListener(() => {
  19. disconnected = true
  20. })
  21. const bridge = new Bridge({
  22. listen (fn) {
  23. port.onMessage.addListener(fn)
  24. },
  25. send (data) {
  26. if (!disconnected) {
  27. port.postMessage(data)
  28. }
  29. }
  30. })
  31. // 3. send a proxy API to the panel
  32. cb(bridge)
  33. })
  34. },
  35. /**
  36. * Register a function to reload the devtools app.
  37. *
  38. * @param {Function} reloadFn
  39. */
  40. onReload (reloadFn) {
  41. chrome.devtools.network.onNavigated.addListener(reloadFn)
  42. }
  43. })
  44. /**
  45. * Inject a globally evaluated script, in the same context with the actual
  46. * user app.
  47. *
  48. * @param {String} scriptName
  49. * @param {Function} cb
  50. */
  51. function injectScript (scriptName, cb) {
  52. const src = `
  53. (function() {
  54. var script = document.constructor.prototype.createElement.call(document, 'script');
  55. script.src = "${scriptName}";
  56. document.documentElement.appendChild(script);
  57. script.parentNode.removeChild(script);
  58. })()
  59. `
  60. chrome.devtools.inspectedWindow.eval(src, function (res, err) {
  61. if (err) {
  62. console.log(err)
  63. }
  64. cb()
  65. })
  66. }