detect.js 1.7 KB

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