Home-Toolbox-Plugin/contents/read.ts

92 lines
2.1 KiB
TypeScript

const getAuthor = () => {
const metaAuthor = document.querySelector<HTMLMetaElement>(`meta[name="author"]`);
const metaOgAuthor = document.querySelector<HTMLMetaElement>(`meta[property="og:article:author"]`);
if (metaAuthor) {
return metaAuthor.getAttribute("content");
}
if (metaOgAuthor) {
return metaOgAuthor.getAttribute("content");
}
return "";
}
const getImage = () => {
const metaOgImage = document.querySelector<HTMLMetaElement>(`meta[property="og:image"]`);
if (metaOgImage) {
return metaOgImage.getAttribute("content");
}
return "";
}
const getDesc = () => {
const articleFirstParagraph = document.querySelector<HTMLParagraphElement>("article p") || document.querySelector<HTMLParagraphElement>("p");
const metaDescription = document.querySelector<HTMLMetaElement>(`meta[name="description"]`);
const metaOgDescription = document.querySelector<HTMLMetaElement>(`meta[property="og:description"]`);
if (metaOgDescription) {
return metaOgDescription.getAttribute("content");
}
if (metaDescription) {
return metaDescription.getAttribute("content");
}
if (articleFirstParagraph) {
return articleFirstParagraph.innerText;
}
return "";
}
const getSiteName = () => {
const title = document.title;
const metaSiteName = document.querySelector<HTMLMetaElement>(`meta[property="og:site_name"]`);
if (metaSiteName) {
return metaSiteName.getAttribute("content");
}
if (title.includes(" - ")) {
const start = title.lastIndexOf(" - ") + 3;
return title.substring(start);
}
if (title.includes(" | ")) {
const start = title.lastIndexOf(" | ") + 3;
return title.substring(start);
}
return "";
}
const getFrom = () => {
if (location.host === "mp.weixin.qq.com") {
return "wechat";
}
return "web";
}
chrome.runtime.onMessage.addListener((req, sender, send) => {
console.log(req);
if (req.type === "toolbox:getInfo") {
send({
title: document.title,
link: `${location.origin}${location.pathname}`,
desc: getDesc(),
from: getFrom(),
author: getAuthor(),
image: getImage(),
sitename: getSiteName(),
});
}
});