Anonymous
Расширение LocalStorage Chrome
Сообщение
Anonymous » 24 янв 2025, 22:34
В настоящее время я работаю над расширением для Chrome, защищающим от рыбалки, но каждый раз, когда я пытаюсь добавить URL-адрес в белый список, расширение приводит к ошибке. вот код моего фона.js:
Код: Выделить всё
const API_KEY = "api_key";
async function checkUrl(url) {
const apiUrl = `https://safebrowsing.googleapis.com/v4/threatMatches:find?key=${API_KEY}`;
const requestBody = {
client: {
clientId: "theantifishing",
clientVersion: "1.0",
},
threatInfo: {
threatTypes: ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"],
platformTypes: ["ANY_PLATFORM"],
threatEntryTypes: ["URL"],
threatEntries: [{ url: url }],
},
};
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
console.error(`HTTP error! status: ${response.status}`);
return false;
}
const data = await response.json();
if (data.matches && data.matches.length > 0) {
return true;
}
return false;
} catch (error) {
console.error("Ошибка при проверке URL:", error);
return false;
}
}
chrome.webNavigation.onCompleted.addListener(async (details) => {
if (details.frameId !== 0) {
return;
}
const url = details.url;
console.log(`Проверка URL: ${url}`);
const isThreat = await checkUrl(url);
if (isThreat) {
console.log(`URL ${url} является фишинговым!`);
chrome.scripting.executeScript({
target: { tabId: details.tabId },
function: () => {
const whitelist = JSON.parse(localStorage.getItem('whitelist')) || [];
if (whitelist.includes(url)) {
return;
}
document.body.innerHTML = '';
document.body.style.cssText = 'margin: 0;';
let div = document.createElement('div');
let buttonAddToWhiteList = document.createElement('button');
buttonAddToWhiteList.textContent = "Все равно перейти";
buttonAddToWhiteList.style.cssText = 'border: none; background-color:rgb(41, 214, 119); border-radius: 5px; color: #f1faee; width: 10rem; height: 3rem; margin-top: 2rem; cursor: pointer;';
buttonAddToWhiteList.addEventListener("click", function() {
whitelist.push(url);
localStorage.setItem('whitelist', JSON.stringify(whitelist));
window.location.reload();
});
div.style.cssText = 'display: flex; margin: 0; justify-content: center; align-items: center; width: 100vw; height: 100vh; font-size: 30px; font-weight: bold; text-align: center; background-color: #e63946; color: #f1faee; font-family: Arial, Helvetica, sans-serif; flex-direction: column;';
div.textContent = 'Сайт заблокирован из-за фишинга!';
div.appendChild(buttonAddToWhiteList);
document.body.append(div);
},
});
} else {
console.log(`URL ${url} безопасен.`);
}
});
А вот мой манифест.json:
Код: Выделить всё
{
"manifest_version": 3,
"name": "The Antifishing",
"version": "1.0",
"description": "The Antifishing - powerful chrome-based extension that helps users easily recognize fishing websites. It also contains a wide range of useful functions and has a user-friendly interface so everyone would be able to use it",
"permissions": [
"activeTab",
"storage",
"scripting",
"tabs",
"webNavigation"
],
"host_permissions" : [
""
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": [""],
"js": ["content.js"]
}
],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/icon-16.png",
"32": "images/icon-32.png",
"48": "images/icon-48.png",
"128": "images/icon-128.png"
}
},
"icons": {
"16": "images/icon-16.png",
"32": "images/icon-32.png",
"48": "images/icon-48.png",
"128": "images/icon-128.png"
}
}
Я учусь в 8-м классе и только начала изучать английский язык, надеюсь, вы поможете с моей проблемой.
Подробнее здесь:
https://stackoverflow.com/questions/793 ... -extension
1737747270
Anonymous
В настоящее время я работаю над расширением для Chrome, защищающим от рыбалки, но каждый раз, когда я пытаюсь добавить URL-адрес в белый список, расширение приводит к ошибке. вот код моего фона.js: [code]const API_KEY = "api_key"; async function checkUrl(url) { const apiUrl = `https://safebrowsing.googleapis.com/v4/threatMatches:find?key=${API_KEY}`; const requestBody = { client: { clientId: "theantifishing", clientVersion: "1.0", }, threatInfo: { threatTypes: ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"], platformTypes: ["ANY_PLATFORM"], threatEntryTypes: ["URL"], threatEntries: [{ url: url }], }, }; try { const response = await fetch(apiUrl, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(requestBody), }); if (!response.ok) { console.error(`HTTP error! status: ${response.status}`); return false; } const data = await response.json(); if (data.matches && data.matches.length > 0) { return true; } return false; } catch (error) { console.error("Ошибка при проверке URL:", error); return false; } } chrome.webNavigation.onCompleted.addListener(async (details) => { if (details.frameId !== 0) { return; } const url = details.url; console.log(`Проверка URL: ${url}`); const isThreat = await checkUrl(url); if (isThreat) { console.log(`URL ${url} является фишинговым!`); chrome.scripting.executeScript({ target: { tabId: details.tabId }, function: () => { const whitelist = JSON.parse(localStorage.getItem('whitelist')) || []; if (whitelist.includes(url)) { return; } document.body.innerHTML = ''; document.body.style.cssText = 'margin: 0;'; let div = document.createElement('div'); let buttonAddToWhiteList = document.createElement('button'); buttonAddToWhiteList.textContent = "Все равно перейти"; buttonAddToWhiteList.style.cssText = 'border: none; background-color:rgb(41, 214, 119); border-radius: 5px; color: #f1faee; width: 10rem; height: 3rem; margin-top: 2rem; cursor: pointer;'; buttonAddToWhiteList.addEventListener("click", function() { whitelist.push(url); localStorage.setItem('whitelist', JSON.stringify(whitelist)); window.location.reload(); }); div.style.cssText = 'display: flex; margin: 0; justify-content: center; align-items: center; width: 100vw; height: 100vh; font-size: 30px; font-weight: bold; text-align: center; background-color: #e63946; color: #f1faee; font-family: Arial, Helvetica, sans-serif; flex-direction: column;'; div.textContent = 'Сайт заблокирован из-за фишинга!'; div.appendChild(buttonAddToWhiteList); document.body.append(div); }, }); } else { console.log(`URL ${url} безопасен.`); } }); [/code] А вот мой манифест.json: [code]{ "manifest_version": 3, "name": "The Antifishing", "version": "1.0", "description": "The Antifishing - powerful chrome-based extension that helps users easily recognize fishing websites. It also contains a wide range of useful functions and has a user-friendly interface so everyone would be able to use it", "permissions": [ "activeTab", "storage", "scripting", "tabs", "webNavigation" ], "host_permissions" : [ "" ], "background": { "service_worker": "background.js" }, "content_scripts": [ { "matches": [""], "js": ["content.js"] } ], "action": { "default_popup": "popup.html", "default_icon": { "16": "images/icon-16.png", "32": "images/icon-32.png", "48": "images/icon-48.png", "128": "images/icon-128.png" } }, "icons": { "16": "images/icon-16.png", "32": "images/icon-32.png", "48": "images/icon-48.png", "128": "images/icon-128.png" } } [/code] Я учусь в 8-м классе и только начала изучать английский язык, надеюсь, вы поможете с моей проблемой. Подробнее здесь: [url]https://stackoverflow.com/questions/79385447/localstorage-chrome-extension[/url]