scrapbox-url-customizer-2
/icons/hr.icon
外部serverを経由せずにweb pageのデータを取得する
utf-8以外のweb pageのデータも文字化けせずに取得できる
web pageごとに変換処理を簡単に変えられるようになった
https://gyazo.com/0e42860aa0c5ecee7259b4f0dfd65fc5
2021-06-10 15:46:53 updated a library
code
takker.icon用にコピペした
code:script.js
import {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 '';// 入力しやすいよう選択範囲を先に消しておく
},
});
code:convert.js
export 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++) {
}
//console.log(map);
const result = text.replace(/https?:\/\/\S+/g, match => mapmatch ?? match); //console.log(result);
return result;
}
async function convert(url, config) {
if (!window.fetchURLInfo) {
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)}];
}