scrapbox-url-customizer-2
外部serverを経由せずにweb pageのデータを取得する
utf-8以外のweb pageのデータも文字化けせずに取得できる
web pageごとに変換処理を簡単に変えられるようになった
2021-06-10 15:46:53 updated a library
code
用にコピペした
script.jsimport {convertWholeText} from './convert.js';
import {insertText} from '../scrapbox-insert-text-2/script.js';
export const execute = (config = []) =>
scrapbox.PopupMenu.addButton({
title: text => /https?:\/\/\S+/.test(text) ? 'URL' : '',// URLがなければボタンを押しにくくする
onClick: text => {
if (!/https?:\/\/\S+/.test(text)) return; // URLがなければ何もしない
convertWholeText(text, config).then(text => insertText(text));
return '';// 入力しやすいよう選択範囲を先に消しておく
},
});
convert.jsexport async function convertWholeText(text, config = []) {
const urls = text.match(/https?:\/\/\S+/g) ?? [];
if (urls.length === 0) return undefined;
const links = await Promise.all(urls.map(url => convert(url, config)));
let map = {};
for (let i = 0; i < urls.length; i++) {
if (!links[i]) break;
map[urls[i]]= links[i];
}
//console.log(map);
const result = text.replace(/https?:\/\/\S+/g, match => map[match] ?? match);
//console.log(result);
return result;
}
async function convert(url, config) {
if (!window.fetchURLInfo) {
alert('Please install "fetchURLInfo" from https://scrapbox.io/programming-notes/url-info-proxy');
return;
}
// hashを分離する
const urlObj = new URL(url);
//console.log(urlObj);
let hash = urlObj.hash !== '' ? decodeURIComponent(urlObj.hash).slice(1) : ''; // #をとる
let pureURL = `${urlObj.origin}${urlObj.pathname}${urlObj.search}`;
const {title, meta, DOM} = await fetchURLInfo(pureURL, {DOM: true});
//console.log({title, meta, DOM});
return (config.find(({match}) => match.test(url))?.text ?? defaultConfig)({
url: decodeURIComponent(url),
pureURL: decodeURIComponent(pureURL),
title,
hash,
meta,
dom: DOM,
});
}
const format = text => text
.trim().replace(/[\n\r\f]/g, '').replace(' ?[', '[').replace('] ?', ']');
function defaultConfig({url, title, hash, dom}) {
if (!title) return url;
const subtitle = dom.getElementById(hash)?.textContent;
return subtitle ?
`[${url} ${format(subtitle)} | ${format(title)}]` :
`[${url} ${format(title)}]`;
}