usePreview.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { ref, Ref } from "@nuxtjs/composition-api"
  2. export default function usePreview(
  3. previewEnabledDefault: boolean,
  4. responseBodyText: Ref<string>
  5. ): {
  6. previewFrame: any
  7. previewEnabled: Ref<boolean>
  8. togglePreview: () => void
  9. } {
  10. const previewFrame = ref<any | null>(null)
  11. const previewEnabled = ref(previewEnabledDefault)
  12. const url = ref("")
  13. const togglePreview = () => {
  14. previewEnabled.value = !previewEnabled.value
  15. if (previewEnabled.value) {
  16. if (previewFrame.value.getAttribute("data-previewing-url") === url.value)
  17. return
  18. // Use DOMParser to parse document HTML.
  19. const previewDocument = new DOMParser().parseFromString(
  20. responseBodyText.value,
  21. "text/html"
  22. )
  23. // Inject <base href="..."> tag to head, to fix relative CSS/HTML paths.
  24. previewDocument.head.innerHTML =
  25. `<base href="${url.value}">` + previewDocument.head.innerHTML
  26. // Finally, set the iframe source to the resulting HTML.
  27. previewFrame.value.srcdoc = previewDocument.documentElement.outerHTML
  28. previewFrame.value.setAttribute("data-previewing-url", url.value)
  29. }
  30. }
  31. return {
  32. previewFrame,
  33. previewEnabled,
  34. togglePreview,
  35. }
  36. }