Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Moises Edson Yañez Villa - Reto #26

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions background.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
let jobs = [];
let start = false;

const saveObjectInlocalStorage = async function (obj) {
return new Promise((resolve, reject) => {
try {
chrome.storage.local.set({ jobs: obj });
} catch (ex) {
reject(ex);
}
});
};

const getObjectInlocalStorage = async function (obj) {
return new Promise((resolve, reject) => {
try {
chrome.storage.local.get(obj, function (value) {
resolve(value);
});
} catch (ex) {
reject(ex);
}
});
};

function addPageToURL(url) {
const regex = /page=(\d+)/;
const match = url.match(regex);
const page = (match && match[1]) || "1";
const newPage = parseInt(page) + 1;
if (!match) {
return url + `&page=${newPage}`;
}
return url.replace(regex, `page=${newPage}`);
}

async function changeTabToNextPage(url, tabid) {
const newURL = addPageToURL(url);
await chrome.tabs.update(tabid, { url: newURL });
}

const filterJobsByCity = (jobs) => {
const newJobs = {};
jobs.forEach(({ city, salary }) => {
if (!newJobs[city]) {
newJobs[city] = {};
}
if (newJobs[city][salary]) {
newJobs[city][salary] += 1;
} else {
newJobs[city][salary] = 1;
}
});
return newJobs;
};

chrome.runtime.onConnect.addListener(function (port) {
port.onMessage.addListener(async function (params, sender) {
const { cmd } = params;
if (cmd === "start") {
jobs = [];
start = true;
const [tab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});
let port = chrome.tabs.connect(tab.id, {
name: "backgroud-content_script",
});
port.postMessage({ cmd: "scrap" });
}
if (cmd === "online") {
const {
sender: {
tab: { id },
},
} = sender;
if (start) {
let port = chrome.tabs.connect(id, {
name: "backgroud-content_script",
});
port.postMessage({ cmd: "scrap" });
}
}
if (cmd === "getInfo") {
const { jobsInformation, nextPage } = params;
jobs = [...jobs, ...jobsInformation];
if (nextPage) {
const {
sender: {
tab: { url, id },
},
} = sender;
changeTabToNextPage(url, id);
} else {
start = false;
saveObjectInlocalStorage(filterJobsByCity(jobs));
port.postMessage({ cmd: "finish", data: filterJobsByCity(jobs) });
}
}
});
});
75 changes: 75 additions & 0 deletions contentscript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
console.log("Ejecutandose el content script 1.0");

function getJobInformation() {
const jobs = Array.from(document.querySelectorAll("[id*='jobcard-']"));
const getJobs = jobs.map((job) => {
const [
{ href: link },
{
children: [
{
children: [
{ innerText: date },
{ innerText: title },
{ innerText: salary },
{ innerText: beneficios },
{
children: [elementEnterpriseCity],
},
] = null,
} = {},
] = null,
},
] = job.children;

const enterprise = elementEnterpriseCity?.querySelector("label")?.innerText;
const city = elementEnterpriseCity?.querySelector("p")?.innerText;

return {
link,
date,
title,
salary,
beneficios,
enterprise,
city,
};
});

return getJobs;
}

function filterJobs(jobs) {
const JobsFilterBySalaryAndCity = jobs.filter((job) => {
return job.salary.toString().search(/[\d]/) >= 0 && job.city;
});

return JobsFilterBySalaryAndCity;
}

const portBackground = chrome.runtime.connect({ name: "content-background" });

portBackground.postMessage({ cmd: "online" });

chrome.runtime.onConnect.addListener(function (port) {
port.onMessage.addListener(({ cmd }) => {
if (cmd === "scrap") {
const jobsInformation = getJobInformation();
const buttonNext = document.querySelector("[class*=next]");
const nextPage = !buttonNext.className.includes("disable");

portBackground.postMessage({
cmd: "getInfo",
jobsInformation: filterJobs(jobsInformation),
nextPage,
});
}
});
});

const port = chrome.runtime.connect({ name: "contenct-popup" });
portBackground.onMessage.addListener(async ({ cmd, data }) => {
if (cmd === "finish") {
port.postMessage({ cmd, data });
}
});
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.
23 changes: 23 additions & 0 deletions manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "scraping-occ",
"description": "Obtener avisos",
"manifest_version": 3,
"version": "1.0",
"permissions": ["activeTab", "scripting", "tabs", "storage"],
"background": {
"service_worker": "background.js",
"type": "module"
},
"content_scripts": [
{
"matches": ["https://www.occ.com.mx/*"],
"js": ["./contentscript.js"]
}
],
"action": {
"default_popup": "./popup/index.html"
},
"icons": {
"32": "./images/icon.png"
}
}
17 changes: 17 additions & 0 deletions popup/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body style="width: 400px">
<button id="btncomunicacion">Filtrar Trabajos</button>
<!-- <button id="btncomunicacionbckg">Enviar hola al background</button> -->
<div id="jobs">
<p id="mensajes">Obteniendo trabajos...</p>
</div>
<script src="index.js"></script>
</body>
</html>
32 changes: 32 additions & 0 deletions popup/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const btnScripting = document.getElementById("btncomunicacion");
const pMensaje = document.getElementById("mensajes");
const jobsDiv = document.getElementById("jobs");

btnScripting.addEventListener("click", async () => {
const port = chrome.runtime.connect({ name: "popup-background" });
port.postMessage({ cmd: "start" });
});

chrome.runtime.onConnect.addListener(function (port) {
port.onMessage.addListener(({ cmd, data }) => {
if (cmd === "finish") {
jobsDiv.removeChild(pMensaje);
let child = document.createElement("p");
child.innerHTML = getString(data);
jobsDiv.appendChild(child);
}
});
});

function getString(data) {
text = "";
cities = Object.keys(data);
cities.forEach((city) => {
this.text += `<strong>Pais/Ciudad</strong>: ${city}<br>`;
Object.keys(data[city]).forEach((salary) => {
this.text += `<strong>Salario :</strong> ${salary} <strong>Cantidad : </strong>${data[city][salary]}<br>`;
});
this.text += "<br>";
});
return this.text;
}