Chrome字体插件

发布时间 2023-11-01 20:27:45作者: Yofoo

FontsChanger字体插件可以强制修改字体, 但是一些等宽字体被替换后效果不好, 可手动修改代码

background.js

const getFont = () => new Promise(ok => chrome.fontSettings.getFont({ genericFamily: "standard"}, ({fontId}) => ok(fontId)));
const getFontFix = () => new Promise(ok => chrome.fontSettings.getFont({ genericFamily: "fixed"}, ({fontId}) => ok(fontId)));

....

function injectFont(tabId, fontId, fontIdFix){
	try{
		const code = 
			"if(typeof UpdateFontBody === 'function')" + 
			"  UpdateFontBody(" + JSON.stringify(chrome.runtime.id) + ", " + JSON.stringify(fontId) + ", " + JSON.stringify(fontIdFix) + ");";
		chrome.tabs.executeScript(tabId, {code,		});
	}catch(e){}
}

content.js

var		font_main="";
var		font_fixed="";


function isEmpty(value) 
{
  return typeof value === 'undefined' || value === null;
}

function GetAllStyle(callback, param)
{
	let 	ets;
	let 	et, rus, sty;
	let		shts;
	let 	i, j;
		
	shts = document.styleSheets;
	for(i=0; i<shts.length; i++)
	{
		rus = shts[i].cssRules;
		if(isEmpty(rus))
			continue;
		for(j=0; j<rus.length; j++)
		{
			sty = rus[j].style;
			if(sty != null)
				callback(sty, param);
		}
	}
}

function strRemoveChar(str, ch) 
{
  return str.split('').filter(
	  function (c) 
	  {
	    return c !== ch;
	  }).join('');
}

function GetFontMain(fontfm)
{
	let		fm1, fm2, sf;
	
	if(fontfm.indexOf("var") != -1)
		return "";
	if(fontfm.indexOf("inherit") != -1)
		return "";
	
	fm1 = strRemoveChar(fontfm, '"');
	sf = fm1.split(',');
	fm2 = sf ? sf[0] : fm1;
	return fm2;
}

function GetNewFont(fontfm)
{
	let		fmnew, fmold;
	let		i;
	let		fixlist = ["courier", "courier new", "consolas", "fixedsys", "monospace"];
	let		comlist = ["arial", "宋体", "tahoma"];
	
	fmold = GetFontMain(fontfm);
	if(fmold == "")
		return "";
	
	fmold = fmold.toLowerCase();
	for(i=0; i<fixlist.length; i++)
	{
		if(fixlist[i] == fmold)
			return font_fixed;
	}
	for(i=0; i<comlist.length; i++)
	{
		if(comlist[i] == fmold)
			return font_main;
	}

	return "";
}

function StyleProc(sty, param)
{
	let 	fontfm, fmnew;
	
	if(isEmpty(sty))
		return;
	
	fontfm = sty.fontFamily;
	if(!fontfm)
		return;

	console.log("fontFamily: " + fontfm);
	fmnew = GetNewFont(fontfm);
	if(fmnew == "")
	{
		console.log("fontFamily: " + fontfm);
		return;
	}
	
	sty.fontFamily = fmnew;
	console.log("fontFamily: " + fontfm + "   ->    " + fmnew);
}
	
function UpdateFontBody(stid, fontMain, fontFix)
{
	let style = document.querySelector(stid);
	if(!style){
		style = document.createElement("style");
		style.id = stid;
		document.head.appendChild(style);
	}
	let st_ext = `
    html, body{font-family: '${fontMain}'!important;}
    *:not([class*='fa-']){font-family: '${fontMain}';}
`;
	font_main = fontMain;
	font_fixed = fontFix;
	
	if(0)	//	强制用固定字体
	{
		style.innerHTML = st_ext;
	}
	else
	{
		GetAllStyle(StyleProc, this);
	}
}