53 lines
1.4 KiB
JavaScript
53 lines
1.4 KiB
JavaScript
function fontLinkToBase64(link) {
|
|
return new Promise(function(resolve, reject) {
|
|
$.get(link, function(data, status, xhr){
|
|
var contentType = xhr.getResponseHeader('content-type');
|
|
const base64Data = 'data:' + contentType + ';charset=utf-8;base64,' + btoa(unescape(encodeURIComponent(data)));
|
|
const dataObj = {
|
|
link: link,
|
|
base64: base64Data
|
|
}
|
|
resolve(dataObj);
|
|
});
|
|
});
|
|
}
|
|
|
|
function getProcessedCSS(css) {
|
|
return new Promise(function(resolve, reject) {
|
|
const fontLinkRegex = new RegExp(/(https?:\/\/(fonts\.)[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,})\w/, 'ig');
|
|
const matches = css.match(fontLinkRegex);
|
|
|
|
// BUG: the last url always throws errors when converted to base64 for some reason.
|
|
matches.splice(-1,1);
|
|
|
|
var promises = [];
|
|
|
|
matches.forEach(function(link) {
|
|
promises.push(fontLinkToBase64(link));
|
|
});
|
|
|
|
Promise.all(promises).then(function(fontData) {
|
|
fontData.forEach(function(data) {
|
|
css = css.replace(data.link, data.base64);
|
|
});
|
|
resolve(css);
|
|
});
|
|
});
|
|
}
|
|
|
|
window.onload = function() {
|
|
|
|
const fontInput = $('#font-input');
|
|
const textarea = $('#processed-css');
|
|
|
|
$('#font-btn').on('click', function() {
|
|
const url = fontInput.val();
|
|
|
|
$.get(url, function(css) {
|
|
getProcessedCSS(css).then(function(processedCSS) {
|
|
textarea.val(processedCSS);
|
|
});
|
|
});
|
|
});
|
|
|
|
};
|