Browser extension that demonstrates the Web Annotation Discovery mechanism: subscribe to people’s annotation collections/‘feeds’, to see their notes on the web; and create & publish annotations yourself.

web-annotation-discovery-we.../src/background/ detect-annotation.ts
61 lines
1.7 KiB

  1. import { isAnnotationMimeType } from '../discovery';
  2. import notify from '../util/notify';
  3. import { AnnotationSource } from '../storage/AnnotationSource';
  4. // When the user navigates to an annotation (collection) directly, suggest
  5. // whether they want to import the annotation(s).
  6. function onHeadersReceived({
  7. responseHeaders,
  8. url,
  9. }: {
  10. responseHeaders?: browser.webRequest.HttpHeaders;
  11. url: string;
  12. }) {
  13. const isAnnotation = responseHeaders?.some(
  14. (header) =>
  15. header.name.toLowerCase() === 'content-type' &&
  16. header.value &&
  17. isAnnotationMimeType(header.value),
  18. );
  19. if (isAnnotation) {
  20. notify({
  21. title: 'Import Web Annotation(s)',
  22. iconUrl: '/assets/icon/icon.svg',
  23. message:
  24. 'You opened a Web Annotation (Collection). Click here to import it to your annotation library.',
  25. onClicked() {
  26. // Note we do not have the response yet at this point. For simplicity, just
  27. // add it as an (inactive) source, then it will be fetched again.
  28. AnnotationSource.addSource(
  29. {
  30. type: 'container',
  31. url,
  32. title: 'Manually imported annotation',
  33. },
  34. false,
  35. );
  36. },
  37. });
  38. }
  39. }
  40. browser.webRequest.onHeadersReceived.addListener(
  41. onHeadersReceived,
  42. {
  43. urls: ['<all_urls>'],
  44. types: ['main_frame'],
  45. },
  46. ['responseHeaders'],
  47. );
  48. // As files loaded through file://… URLs do not have headers, we run a separate check for these.
  49. async function onVisitFileUrl({ url, tabId }: { url: string; tabId: number }) {
  50. // TODO (likely to be quite a hassle, if possible at all..)
  51. }
  52. browser.webNavigation.onCommitted.addListener(onVisitFileUrl, {
  53. url: [{ schemes: ['file'] }],
  54. });