detect.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 (header(win.header) || match(win.url)) {
  30. if (onwakeup && chrome.webRequest) {
  31. onwakeup = false
  32. chrome.tabs.reload(id)
  33. }
  34. else {
  35. inject()
  36. }
  37. }
  38. })
  39. }
  40. }
  41. var header = (value) => {
  42. return state.header && value && /text\/(?:x-)?markdown/i.test(value)
  43. }
  44. var match = (url) => {
  45. var location = new URL(url)
  46. var origin =
  47. state.origins[location.origin] ||
  48. state.origins['*://' + location.host] ||
  49. state.origins['*://*']
  50. // ff: webRequest bug - does not match on `hostname:port`
  51. if (!origin && /Firefox/.test(navigator.userAgent)) {
  52. var origin =
  53. state.origins[location.protocol + '//' + location.hostname] ||
  54. state.origins['*://' + location.hostname] ||
  55. state.origins['*://*']
  56. }
  57. if (origin && origin.match && new RegExp(origin.match).test(location.href)) {
  58. return origin
  59. }
  60. }
  61. return {tab, header, match}
  62. }