Update dependencies and refactor useMessage hook

This commit is contained in:
n4ze3m
2024-03-24 23:56:41 +05:30
parent 01d27fd1c2
commit 2381588e72
6 changed files with 752 additions and 518 deletions

View File

@@ -1,15 +1,46 @@
import { pdfDist } from "./pdfjs"
const _getHtml = () => {
export const getPdf = async (data: ArrayBuffer) => {
const pdf = pdfDist.getDocument({
data,
useWorkerFetch: false,
isEvalSupported: false,
useSystemFonts: true,
});
pdf.onPassword = (callback: any) => {
const password = prompt("Enter the password: ")
if (!password) {
throw new Error("Password required to open the PDF.");
}
callback(password);
};
const pdfDocument = await pdf.promise;
return pdfDocument
}
const _getHtml = async () => {
const url = window.location.href
// check the content type
if (document.contentType === "application/pdf") {
return { url, content: "", type: "pdf" }
}
const html = Array.from(document.querySelectorAll("script")).reduce(
(acc, script) => {
return acc.replace(script.outerHTML, "")
},
document.documentElement.outerHTML
)
return { url, html }
return { url, content: html, type: "html" }
}
export const getHtmlOfCurrentTab = async () => {
export const getDataFromCurrentTab = async () => {
const result = new Promise((resolve) => {
chrome.tabs.query({ active: true, currentWindow: true }, async (tabs) => {
const tab = tabs[0]
@@ -25,9 +56,41 @@ export const getHtmlOfCurrentTab = async () => {
})
}) as Promise<{
url: string
html: string
content: string
type: string
}>
return result
const { content, type, url } = await result
if (type === "pdf") {
const res = await fetch(url)
const data = await res.arrayBuffer()
let pdfHtml: string[] = []
const pdf = await getPdf(data)
for (let i = 1; i <= pdf.numPages; i += 1) {
const page = await pdf.getPage(i);
const content = await page.getTextContent();
if (content?.items.length === 0) {
continue;
}
const text = content?.items.map((item: any) => item.str).join("\n")
.replace(/\x00/g, "").trim();
pdfHtml.push(`<div class="pdf-page">${text}</div>`)
}
return {
url,
content: pdfHtml.join(""),
type: "html"
}
}
return { url, content, type }
}

8
src/libs/pdfjs.ts Normal file
View File

@@ -0,0 +1,8 @@
import * as pdfDist from "pdfjs-dist"
import * as pdfWorker from "pdfjs-dist/build/pdf.worker.mjs";
pdfDist.GlobalWorkerOptions.workerSrc = pdfWorker
export {
pdfDist
}