使用 highlight.js 给代码片断添加语法高亮, 并设置更优雅的字体
当前为
// ==UserScript==
// @name Syntax highlighting
// @namespace http://tampermonkey.net/
// @version 0.1.2
// @description 使用 highlight.js 给代码片断添加语法高亮, 并设置更优雅的字体
// @author floatsyi
// @license MIT
// @require https://cdn.bootcss.com/highlight.js/9.15.10/highlight.min.js
// @require https://cdn.bootcss.com/fontfaceobserver/2.1.0/fontfaceobserver.js
// @match *://*/*
// @grant GM_addStyle
// @grant GM_setValue
// @grant GM_getValue
// @grant unsafeWindow
// ==/UserScript==
// https://www.bootcdn.cn/highlight.js/
// console.log(unsafeWindow.FontFaceObserver)
const envDetection = [unsafeWindow.Prism, unsafeWindow.hljs]
if (envDetection.some(item => !!item)) return false
const themes = [
'atom-one-dark',
'brown-paper',
'color-brewer',
'docco',
'darkula'
]
let currentTheme = themes[0]
const fonts = ['BioRhyme', 'Fira Code', 'Lato']
let currentFont = fonts[1]
const backgroundColor = '#272c34'
const fetchStyleText = url =>
fetch(url, {
headers: {
'Content-Type': 'text/plain'
}
}).then(function (response) {
return response.text()
})
const setStyle = () => {
const themeStyle = GM_getValue(currentTheme)
if (themeStyle) {
GM_addStyle(themeStyle)
} else {
const themeUrl = `https://cdn.bootcss.com/highlight.js/9.15.10/styles/${currentTheme}.min.css`
fetchStyleText(themeUrl).then(function (style) {
GM_addStyle(style)
GM_setValue(currentTheme, style)
})
}
const fontStyle = GM_getValue(currentFont)
if (fontStyle) {
GM_addStyle(fontStyle)
} else {
const fontUrl = `https://fonts.loli.net/css?family=${currentFont}`
fetchStyleText(fontUrl).then(function (style) {
GM_addStyle(style)
GM_setValue(currentFont, style)
})
}
}
const setFont = () => {
const font = new window.FontFaceObserver(currentFont)
font.load().then(
function () {
console.log('Font is available')
for (const pre of Array.from(document.querySelectorAll('pre'))) {
const code = pre.querySelector('code')
window.hljs.highlightBlock(code)
code.style.fontFamily = currentFont
}
},
function () {
console.log('Font is not available')
}
)
}
setStyle()
setFont()
console.log('highlight runing')