Skip to content

Commit

Permalink
Download the markdown from the content script (#65)
Browse files Browse the repository at this point in the history
* Download the markdown from the content script

There are complexities that arise from passing the content to the
background script, especially when moving to Manifest V3. Avoid this by
just triggering the download directly from the content script.

* Simplify the message handler
  • Loading branch information
kfarnung authored Oct 6, 2024
1 parent 99c8808 commit fdb89fd
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 24 deletions.
16 changes: 0 additions & 16 deletions src/background_scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,8 @@ import {
tabs as _tabs,
} from "webextension-polyfill";

function saveAs(text) {
const blob = new Blob([text], { type: "text/markdown;charset=utf-8" });

return downloads.download({
url: URL.createObjectURL(blob),
filename: "README.md",
saveAs: true,
});
}

runtime.onMessage.addListener((data, sender) => {
switch (data.action) {
case "saveAs":
saveAs(data.text).catch((err) => {
console.error("Failed to save content", err);
});
break;

case "showPageAction":
pageAction.show(sender.tab.id);
break;
Expand Down
22 changes: 14 additions & 8 deletions src/content_scripts/to-markdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,16 @@ function expandHrefs(article) {
}
}

function downloadBlob(blob) {
const downloadLink = document.createElement('a');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'README.md';
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
URL.revokeObjectURL(downloadLink.href);
}

function capturePage() {
const newDoc = document.createDocumentFragment();
const titleElement = document.createElement("h1");
Expand Down Expand Up @@ -115,17 +125,13 @@ function capturePage() {
newDoc.appendChild(article);
}

return generateMarkdown(newDoc);
const text = generateMarkdown(newDoc);
const blob = new Blob([text], { type: "text/markdown;charset=utf-8" });
downloadBlob(blob);
}

runtime.onMessage.addListener((data) => {
if (data.action === "capturePage") {
const markdown = capturePage();
return runtime
.sendMessage({
action: "saveAs",
text: markdown,
})
.catch((err) => console.error("Failed to send 'saveAs' message", err));
capturePage();
}
});
3 changes: 3 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@ module.exports = {
path: path.resolve(__dirname, "addon"),
filename: "[name]/index.js",
},
optimization: {
minimize: false,
},
};

0 comments on commit fdb89fd

Please sign in to comment.