detect.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. md.detect = ({storage: {state}, inject}) => {
  2. var onwakeup = true
  3. var code = `
  4. JSON.stringify({
  5. url: window.location.href,
  6. header: document.contentType,
  7. loaded: !!window.state,
  8. })
  9. `
  10. var tab = (id, info, tab) => {
  11. if (info.status === 'loading') {
  12. // try
  13. chrome.tabs.executeScript(id, {code, runAt: 'document_start'}, (res) => {
  14. if (chrome.runtime.lastError) {
  15. // origin not allowed
  16. return
  17. }
  18. try {
  19. var win = JSON.parse(res)
  20. }
  21. catch (err) {
  22. // JSON parse error
  23. return
  24. }
  25. if (win.loaded) {
  26. // anchor
  27. return
  28. }
  29. if (match(win.header, win.url)) {
  30. if (onwakeup && state.csp) {
  31. onwakeup = false
  32. chrome.tabs.reload(id)
  33. }
  34. else {
  35. inject()
  36. }
  37. }
  38. })
  39. }
  40. }
  41. var match = (header, url) => {
  42. if (state.header && header && /text\/(?:x-)?markdown/i.test(header)) {
  43. return true
  44. }
  45. else {
  46. var location = new URL(url)
  47. var path =
  48. state.origins[location.origin] ||
  49. state.origins['*://' + location.host] ||
  50. state.origins['*://*']
  51. // ff: webRequest bug - does not match on `hostname:port`
  52. if (!path && /Firefox/.test(navigator.userAgent)) {
  53. var path =
  54. state.origins[location.protocol + '//' + location.hostname] ||
  55. state.origins['*://' + location.hostname] ||
  56. state.origins['*://*']
  57. }
  58. if (path && new RegExp(path).test(location.href)) {
  59. return true
  60. }
  61. }
  62. }
  63. return {tab, match}
  64. }