Skip to content
This repository has been archived by the owner on Dec 19, 2024. It is now read-only.

Commit

Permalink
Merge pull request #1 from DxsarzUnion/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
xXxCLOTIxXx authored Jun 1, 2024
2 parents c6da63d + 1fe74d9 commit 31bb3a4
Show file tree
Hide file tree
Showing 12 changed files with 296 additions and 73 deletions.
109 changes: 89 additions & 20 deletions background.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,98 @@
let isEnabled = false;
async function getCurrentTabUrl() {
try {
const tabs = await browser.tabs.query({ active: true, currentWindow: true });
const currentTab = tabs[0];
return currentTab.url;
} catch (error) {
console.error(`Ошибка при получении URL текущей вкладки: ${error}`);
return null;
}
}

function toggleExtension() {
isEnabled = !isEnabled;
updateBadge();
function checkPage(currentUrl) {
if (currentUrl && currentUrl.startsWith("https://naurok.com.ua")) {
if (currentUrl.includes("/test/testing/")) {
return true;
}
}
return false;
}

function updateBadge() {
browser.browserAction.setBadgeText({ text: isEnabled ? "ON" : "OFF" });
function errorCurrentTab() {
browser.notifications.create({
"type": "basic",
"title": "TabError",
"message": "Текущая страница не является запущенным тестом сайта naurok.ua"
});
}

function getActiveStatus() {
return isEnabled;
function error(msg){
browser.notifications.create({
type: 'basic',
title: 'Error',
message: msg
});
}
updateBadge()
browser.browserAction.onClicked.addListener(toggleExtension);

browser.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.action === 'toggle') {
toggleExtension();
sendResponse({ isActive: isEnabled });
} else if (message.action === 'getStatus') {
sendResponse({ isActive: isEnabled });
} else if (message.action === 'search') {
if (isEnabled) {
browser.tabs.create({ url: message.url });



function sendDataToPage(tabId, data) {
const scriptCode = `
var jsonData = ${JSON.stringify(data)};
browser.runtime.sendMessage({ action: 'updateData', data: jsonData });
`;

browser.tabs.executeScript(tabId, { code: scriptCode }).then(() => {
//console.log('Данные успешно отправлены на страницу');
}).catch((error) => {
console.error('Ошибка отправки данных на страницу:', error);
});
}
function resultTab(url) {
browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
let activeTab = tabs[0];
if (activeTab) {
//console.log('Отправка сообщения в контентный скрипт', activeTab.id);
browser.tabs.sendMessage(activeTab.id, { action: 'start', url: url })
.then((response) => {
//console.log('Ответ получен:', response.status);
if (response && response.status === false) {
error(response.msg);
return;
}
browser.tabs.create({ url: 'result.html' }).then((tab) => {
//console.log('Новая вкладка создана:', tab.id);
browser.tabs.onUpdated.addListener(function listener(tabId, changeInfo, updatedTab) {
if (tabId === tab.id && changeInfo.status === 'complete') {
//console.log('Страница загружена:', updatedTab.id);
sendDataToPage(tabId, {sourse_url: url, data: response.data});
browser.tabs.onUpdated.removeListener(listener);
}
});
});
})
.catch((error) => {
error('Ошибка отправки сообщения в контентный скрипт:', error);
});
} else {
error('Не удалось найти активную вкладку.');
}
}).catch((error) => {
error('Ошибка при выполнении запроса вкладок:', error);
});
}


browser.browserAction.onClicked.addListener(async (tab) => {
try {
const url = await getCurrentTabUrl();
const isTest = checkPage(url);
if (isTest == true) {
resultTab(url);
} else {
errorCurrentTab();
}
} catch (error) {
console.error('Ошибка при обработке нажатия на кнопку:', error);
}
});
62 changes: 52 additions & 10 deletions content.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,54 @@
function handleClick(event) {
const selectedText = event.target.closest('.test-content-text-inner')?.textContent;
browser.runtime.sendMessage({ action: 'getStatus' }, function(response) {
const isEnabled = response.isActive;
if (selectedText && isEnabled) {
const searchUrl = `https://www.google.com/search?q=${encodeURIComponent(selectedText)}`;
browser.runtime.sendMessage({ action: 'search', url: searchUrl });
}
});

function get_session_id(ngInitValue) {
let initValues = ngInitValue.split(',');
if (initValues.length >= 3) {
return initValues[1].trim();
} else {
return null;
}
}

document.addEventListener('click', handleClick);

async function get_session_info(sessionId) {
try {
let url = `https://naurok.com.ua/api2/test/sessions/${sessionId}`;
let response = await fetch(url);
if (response.ok) {
let jsonResponse = await response.json();
return jsonResponse;
} else {
console.error('Ошибка выполнения запроса:', response.statusText);
return null;
}
} catch (error) {
console.error('Ошибка выполнения запроса:', error);
return null;
}
}


browser.runtime.onMessage.addListener(async (message, sender) => {
console.log('Получено сообщение:', message);
if (message.action !== 'start') {
return{ status: false, msg: 'Некорректный тип действия.' };
}

let xpath = '/html/body/div[1]/div';
let element = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (!element) {
return { status: false, msg: 'Не удалось найти элемент.' };
}

let sID = get_session_id(element.getAttribute('ng-init'));
if (sID === null) {
return { status: false, msg: 'Не удалось получить id сессии.' };

}
let sInfo = await get_session_info(sID);
console.log(sInfo);
if (sInfo === null) {
return{ status: false, msg: 'Не удалось получить информацию о сессии.' };
}

return{ status: true, data: sInfo };
});
18 changes: 18 additions & 0 deletions css/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
.btn {
padding: 10px 20px;
background-color: #80ed99;
color: #fff;
text-decoration: none;
border-radius: 5px;
font-size: 16px;
margin: 2%;
}

.btn:hover {
background-color: #bcffcb;
}


#test_info{
margin-top: 1%;
}
Binary file added images/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified images/icon128.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified images/icon16.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified images/icon64.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 13 additions & 12 deletions manifest.json
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
{
"manifest_version": 2,
"name": "search assistant",
"version": "1.0",
"description": "Helper in finding information from a page.",
"permissions": ["activeTab"],
"name": "Naurok helper",
"version": "1.2",
"description": "Помощник прохождения тестов на сайте naurok.ua",
"permissions": ["activeTab", "tabs", "notifications"],
"background": {
"scripts": ["background.js"],
"type": "module",
"persistent": false
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"browser_action": {
"default_icon": {
"16": "images/icon16.png",
"64": "images/icon64.png",
"128": "images/icon128.png"
},
"default_title": "Search assistant"
"default_title": "Naurok helper"
},
"icons": {
"16": "images/icon16.png",
"64": "images/icon64.png",
"128": "images/icon128.png"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
}
14 changes: 0 additions & 14 deletions popup.html

This file was deleted.

17 changes: 0 additions & 17 deletions popup.js

This file was deleted.

44 changes: 44 additions & 0 deletions result.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<link rel="shortcut icon" href="images/icon64.png" type="image/x-icon">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Naurok Helper</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div style="margin-bottom: 20px; border: 1px solid #ccc; border-radius: 5px; padding: 15px; text-align: center;">
<p style="color: #888;">made by xsarz</p>
<div style="display: flex; justify-content: space-between; flex-wrap: wrap; margin-top: 10px;">
<a href="https://discord.gg/GtpUnsHHT4" target="_blank" style="text-decoration: none; color: #888;">
<button style="background-color: #3b5998; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;">
Discord
</button>
</a>
<a href="https://t.me/DxsarzUnion" target="_blank" style="text-decoration: none; color: #888;">
<button style="background-color: #55acee; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;">
Telegram
</button>
</a>
<a href="https://www.youtube.com/@Xsarzy" target="_blank" style="text-decoration: none; color: #888;">
<button style="background-color: #e4405f; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;">
YouTube
</button>
</a>
<a href="https://github.com/xXxCLOTIxXx" target="_blank" style="text-decoration: none; color: #888;">
<button style="background-color: black; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;">
GitHub
</button>
</a>
</div>
</div>





<div id="data"></div>
<script src="session_handler.js"></script>
</body>
</html>
Loading

0 comments on commit 31bb3a4

Please sign in to comment.