Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eoureo/3d362603c8c4ee4166d8fc2bfdb6079f to your computer and use it in GitHub Desktop.
Save eoureo/3d362603c8c4ee4166d8fc2bfdb6079f to your computer and use it in GitHub Desktop.
Combination of "Obsidian Web Clipper Bookmarklet" and "Local REST API". Obsidian Web Clipper Bookmarklet과 Local REST API의 결합.
javascript: Promise.all([import('https://unpkg.com/turndown@6.0.0?module'), import('https://unpkg.com/@tehshrike/readability@0.2.0'), ]).then(async ([{
default: Turndown
}, {
default: Readability
}]) => {
/* Optional 'Local REST API' Port number */
const REST_API_PORT = 27124;
/* Optional 'Local REST API' key */
const REST_API_KEY = "Put your 'Local REST API' key value here.";
/* Optional vault name */
/* const vault = ""; */
/* Optional folder name such as "Clippings/" */
const folder = "Scraps/";
/* Optional tags */
const tags = "#clippings";
const URL = `https://127.0.0.1:${REST_API_PORT}/vault/${folder}`;
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
const selection = getSelectionHtml();
const {
title,
byline,
content
} = new Readability(document.cloneNode(true)).parse();
function getFileName(fileName) {
var userAgent = window.navigator.userAgent,
platform = window.navigator.platform,
windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];
if (windowsPlatforms.indexOf(platform) !== -1) {
fileName = fileName.replace(':', '').replace(/[/\\?%*|"<>]/g, '-');
} else {
fileName = fileName.replace(':', '').replace(/\//g, '-').replace(/\\/g, '-');
}
return fileName;
}
const fileName = getFileName(title);
if (selection) {
var markdownify = selection;
} else {
var markdownify = content;
}
/*
if (vault) {
var vaultName = '&vault=' + encodeURIComponent(`${vault}`);
} else {
var vaultName = '';
}
*/
const markdownBody = new Turndown({
headingStyle: 'atx',
hr: '---',
bulletListMarker: '-',
codeBlockStyle: 'fenced',
emDelimiter: '*',
}).turndown(markdownify);
var date = new Date();
function convertDate(date) {
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
const today = convertDate(date);
const fileContent =
"author:: " + byline + "\n"
+ "source:: [" + title + "](" + document.URL + ")\n"
+ "clipped:: [[" + today + "]]\n"
+ "published:: \n\n"
+ tags + "\n\n"
+ markdownBody ;
/*
document.location.href = "obsidian://new?"
+ "file=" + encodeURIComponent(folder + fileName)
+ "&content=" + encodeURIComponent(fileContent)
+ vaultName ;
*/
const response = await fetch(URL + fileName + ".md", {
method: "POST",
headers: {
"Content-Type": "text/markdown",
"Authorization": "Bearer " + REST_API_KEY,
},
body: fileContent,
});
/* 에러가 나면 확인 */
if(response.status != 204) {
const response_data = await response.text();
console.log(response_data);
alert("에러(Error)가 나와 추가할 수 없슴니다.\n\n" + response_data);
}
else {
console.log("성공(Success)!")
}
})
.catch((err) => {
alert("에러 발행\n\n" + err);
})
@eoureo
Copy link
Author

eoureo commented Apr 1, 2023

아래 북마크릿은 Obsidian URI를 써서 클리핑 데이터를 옵시디언으로 전송합니다. 그래서 URI 2048 글자 수 제한 때문에 데이터가 조금만 많으면 실행 되지 않습니다. 더욱이 한글은 한글자당 9개 글자수로 변환되어야 하므로 2~400여자가 못되어도 2048 개의 변환 된 글자가 되어 버립니다.

Obsidian Web Clipper Bookmarklet to save articles and pages from the web (for Safari, Chrome, Firefox, and mobile browsers) · GitHub
https://gist.github.com/kepano/90c05f162c37cf730abb8ff027987ca3

"Obsidian Web Clipper Bookmarklet"의 URI 2048 글자 수 제한을 해결하기 위해 옵시디안 플러그인 "Local REST API"를 사용하였습니다.

POST 방식을 사용하여 노트 파일이 없으면 새로 만듭니다. 이미 노트 파일이 있으면 그 노트 파일에 더해집니다.

Local Rest API for Obsidian: Interactive API Documentation  
위 페이지에서 자세한 설명을 볼 수 있습니다.

여기에서 사용하는 fetch 명령은 다른 도메인으로 데이터를 전송하므로 CORS / CSP 보안 설정이 된 사이트에서는 실행되지 않습니다.
이 문제는 북마크릿보다는 웹 브라우저 Extension으로 해결해야 할 것 같습니다.

소스 코드를 읽기 쉽게 하고 처음 만들어진 대로 그대로 두어 비교 하기 쉽게 했습니다.

@eoureo
Copy link
Author

eoureo commented Apr 3, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment