Files
bobbie-vault/Templates/Scripts/bookmark-webclipper.js
2026-03-02 17:06:32 +00:00

92 lines
3.6 KiB
JavaScript

//
// copy this code into this site to create a bookmarklet: https://caiorss.github.io/bookmarklet-maker/
//
javascript: (function () {
if (window.obs_active) return;
window.obs_active = true;
Promise.all([
import('https://unpkg.com/turndown@6.0.0?module'),
import('https://unpkg.com/@tehshrike/readability@0.2.0'),
]).then(async ([{ default: T }, { default: R }]) => {
/* 1. CONFIGURATION */
const vault = "Bobbie's Vault";
const folder = "Library/";
let tags = "clippings"; // disabled lower down
/* 2. DATE & TIME */
const d = new Date();
const pad = (n) => n.toString().padStart(2, '0');
const isoNow = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
const today = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
/* 3. ORIGINAL TAG LOGIC */
if (document.querySelector('meta[name="keywords" i]')) {
var keywords = document.querySelector('meta[name="keywords" i]').getAttribute('content').split(',');
keywords.forEach(function (keyword) {
tags += ' ' + keyword.split(' ').join('');
});
}
/* 4. CONTENT CAPTURE */
const { title, byline, content } = new R(document.cloneNode(true)).parse();
const selection = window.getSelection().toString();
const md = new T({
headingStyle: 'atx',
hr: '---',
bulletListMarker: '-',
codeBlockStyle: 'fenced',
emDelimiter: '*',
}).turndown(selection || content);
/* 5. ORIGINAL METADATA LOGIC */
const getMeta = (attr, val) => {
const el = document.querySelector(`meta[${attr}='${val}']`);
return el ? el.getAttribute("content").trim() : "";
};
const author = byline || getMeta("name", "author") || getMeta("property", "author") || getMeta("property", "og:site_name");
const authorBrackets = author ? `"[[${author}]]"` : "";
const timeEl = document.querySelector("time");
let published = "";
const pubAttr = timeEl ? timeEl.getAttribute("datetime") : "";
if (pubAttr) {
const pD = new Date(pubAttr);
published = `${pD.getFullYear()}-${pad(pD.getMonth() + 1)}-${pad(pD.getDate())}`;
}
/* 6. BUILD YAML & FILE */
const fileContent =
'---\n'
+ 'created: ' + isoNow + '\n'
+ 'up:\n'
+ ' - "[[Library]]"\n'
+ 'title: "' + title + '"\n'
+ 'source: ' + document.URL + '\n'
+ 'author: ' + authorBrackets + '\n'
+ 'published: ' + published + '\n'
+ 'topics: \n'
+ 'tags:\n'
+ '---\n\n'
+ md;
/* 7. SAFE URI CONSTRUCTION */
const fileName = today + " " + title.replace(/[:/\\|?*<>]/g, '-').substring(0, 60).trim();
const uri = `obsidian://new?vault=${encodeURIComponent(vault)}&file=${encodeURIComponent(folder + fileName)}&content=${encodeURIComponent(fileContent)}`;
/* 8. STABLE EXECUTION (IFRAME) */
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = uri;
document.body.appendChild(iframe);
setTimeout(() => {
document.body.removeChild(iframe);
window.obs_active = false;
}, 1000);
});
})();