我創建了一個 chrome 擴展來更改某些網站的默認字體。
清單.json
{
"name": "Custom Font",
"version": "0.0.1",
"description": "A Extension to change default Fonts.",
"manifest_version": 3,
"content_scripts": [
{
"matches": ["https://dev.to/*", "https://github.com/*"],
"js": ["main.js"] // content.js
}
]
}
main.js
const head = document.head || document.getElementsByTagName('head')[0];
const link = document.createElement('link');
link.rel = 'stylesheet';
if (window.location.href.includes('https://dev.to')) {
link.href = chrome.runtime.getURL('devTo.css');
}
if (window.location.href.includes('https://github.com')) {
link.href = chrome.runtime.getURL('github.css');
}
head.appendChild(link);
但是當我嘗試在上述網站中運行上述代碼時,它給了我一個錯誤:
GET chrome-extension://invalid/ net::ERR_FAILED
uj5u.com熱心網友回復:
如果您想從 JavaScript 內容腳本(在您的 Chrome 擴展清單 v3 中)動態添加樣式。你可以這樣做:
如果您想為用戶提供隨時啟用/禁用它的選項,動態添加樣式表是一個好主意。例如,帶有選項頁面。
清單.json
{
"name": "Inject Style",
"action": {},
"manifest_version": 3,
"version": "0.1",
"description": "Inject the stylesheet from content script",
"content_scripts": [
{
"matches": ["https://dev.to/*", "https://github.com/*"],
"js": ["main.js"]
}
],
"permissions": ["activeTab"],
"host_permissions": ["<all_urls>"],
"web_accessible_resources": [
{
"resources": [ "devTo.css"],
"matches": [ "https://dev.to/*" ]
},
{
"resources": [ "github.css"],
"matches": [ "https://github.com/*" ]
}]
}
main.js(內容腳本)
function addstylesheet(filename){
var link = document.createElement("link");
link.href = chrome.runtime.getURL(filename);
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);
}
if(window.location.href.match(/(https:\/\/(.*github\.com\/.*))/i)){
addstylesheet("github.css");
}else if(window.location.href.match(/(https:\/\/(.*dev\.to\/.*))/i)){
addstylesheet("devTo.css");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/442594.html
上一篇:通過影像處理進行彈環檢測
