detect.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. if (!win) {
  22. return
  23. }
  24. }
  25. catch (err) {
  26. // JSON parse error
  27. return
  28. }
  29. if (win.loaded) {
  30. // anchor
  31. return
  32. }
  33. if (detect(win.header, win.url)) {
  34. if (onwakeup && chrome.webRequest) {
  35. onwakeup = false
  36. chrome.tabs.reload(id)
  37. }
  38. else {
  39. inject(id)
  40. }
  41. }
  42. })
  43. }
  44. }
  45. var detect = (content, url) => {
  46. var location = new URL(url)
  47. var origin =
  48. state.origins[location.origin] ||
  49. state.origins[location.protocol + '//' + location.hostname] ||
  50. state.origins['*://' + location.host] ||
  51. state.origins['*://' + location.hostname] ||
  52. state.origins['*://*']
  53. return (
  54. (origin && origin.header && origin.path && origin.match && /\btext\/(?:(?:(?:x-)?markdown)|plain)\b/i.test(content) && new RegExp(origin.match).test(location.href)) ||
  55. (origin && origin.header && !origin.path && /\btext\/(?:(?:(?:x-)?markdown)|plain)\b/i.test(content)) ||
  56. (origin && origin.path && origin.match && !origin.header && new RegExp(origin.match).test(location.href))
  57. ? origin
  58. : undefined
  59. )
  60. }
  61. return {tab}
  62. }