How to read a cookie in chrome extension to make sure user is logged in on my website - google-chrome

I have a user who will log in to my website using credentials (Not google Oauth). Once he is logged in, I want to check if he is logged in on my website using the chrome extension.
Manifest.json
"host_permissions": [
"*://*.mydomain.com/"
],
"permissions": [
"storage",
"cookies"
],
background.js
function getCookies(domain, name, callback) {
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
if(callback) {
callback(cookie.value);
}
});
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
getCookies("mydomain.com", "my_cookie_name", function (cookie_value) {
chrome.extension.getBackgroundPage().console.log(cookie_value)
});
})
Content Script
This sends messages to background.js
chrome.runtime.sendMessage({text, style, platform, isBig: Boolean(element)}, function (response) {
updateInput(response, element);
})
I don't see any log output here. Anything I am doing wrong?

Related

Can't inject JavaScript into new tab from popup.js

I'M creating an extension that autofill's forms on different websites. There is a portion of the script that records the actions of the user with event listeners. After the recording is done the user click the test button that will launch a new tab and autofill's the form. I know launching a new tab for testing is not necessary but this function will be used later for another feature.
This is what I got so far. I had started over several times. I tried sending a message to content script. The chrome.windows,create function only launched from the popup script. I started chrome development a week ago. I'm totally confused.
Popup.js
`(async () =\> { const tab = await chrome.tabs.create({url: 'https://www.listyourself.net/ListYourself/listing.jsp'});
const tabId = tab.id; if (!tab.url)
await onTabUrlUpdated(tabId);
await chrome.scripting.executeScript({
target: {tabId},
files: \['test.js'\],
});`
})();`
I think your extension has two problems.
onTabUrlUpdated is not defined.
Execution of chrome.tabs.create causes the popup to lose focus, so the JavaScript is also terminated.
Here is a sample that fixes it.
manifest.json
{
"manifest_version": 3,
"name": "hoge",
"version": "1.0",
"permissions": [
"scripting"
],
"host_permissions": [
"<all_urls>"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_title": "hoge"
}
}
background.js
chrome.action.onClicked.addListener(() => {
main();
});
const test = () => {
console.log("test");
}
const main = async () => {
const tab = await chrome.tabs.create({ url: "https://nory-soft.web.app/" });
const tabId = tab.id;
if (!tab.url) {
chrome.tabs.onUpdated.addListener((updateTabId, changeInfo) => {
if ((updateTabId == tabId) && (changeInfo.status == "complete")) {
chrome.scripting.executeScript({
target: { tabId },
func: test
});
}
});
}
}

Add PWA to home screen not working on chrome mobile

I recently got into front end developpement to make an interface for a nodejs server hosted on a raspberry pi.
I heard of progressive web app and wanted the user to be able to install it on his phone.
So here are the manifest and the service worker script.
Manifest:
{
"name": "Philips D6330",
"short_name": "Philips D6330",
"description": "A control app for the Philips D6330",
"icons": [
{
"src": "https://192.168.1.26/cdn/favicon.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "https://192.168.1.26",
"display": "fullscreen",
"orientation": "portrait",
"theme_color": "#333333",
"background_color": "#333333",
"scope": "/"
}
Service Worker:
const CACHE_NAME = 'cache';
const CACHE = [
'/',
'/cdn/offline.html',
'/cdn/style.css',
'/cdn/favicon.png',
'/cdn/linetoB.ttf',
'/cdn/linetoL.ttf',
'/cdn/neon.ttf',
'/cdn/not.png',
'/cdn/next.png',
'/cdn/pause.png',
'/cdn/play.png',
'/cdn/previous.png',
'/cdn/dots.png',
'/cdn/rfid.png'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
return cache.addAll(CACHE)
})
.then(self.skipWaiting())
)
})
self.addEventListener('fetch', function(event) {
if (event.request.mode === 'navigate') {
event.respondWith(
fetch(event.request)
.catch(() => {
return caches.open(CACHE_NAME)
.then((cache) => {
return cache.match('/cdn/offline.html');
})
})
);
}
else {
event.respondWith(
fetch(event.request)
.catch(() => {
return caches.open(CACHE_NAME)
.then((cache) => {
return cache.match(event.request)
})
})
);
}
})
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys()
.then((keyList) => {
return Promise.all(keyList.map((key) => {
if (key !== CACHE_NAME) {
console.log('[ServiceWorker] Removing old cache', key)
return caches.delete(key)
}
}))
})
.then(() => self.clients.claim())
)
})
I think also relevant to tell you that all of this happens on my local network so my node server uses https with a self-signed certificate made using this tutorial : https://medium.com/#tbusser/creating-a-browser-trusted-self-signed-ssl-certificate-2709ce43fd15
But even tho it's a self-signed certificate, the service worker seem to registers well on firefox and chrome, as it stores the files and displays the offline page when offline.
Here is my problem :
when I want to install it from the desktop version of chrome I can but not chrome mobile (or samsung internet)...
here is the piece of code i use to make it instalable :
<script defer>
window.addEventListener('beforeinstallprompt', (event) => {
console.log('👍', 'beforeinstallprompt', event);
// Stash the event so it can be triggered later.
window.deferredPrompt = event;
});
butInstall.addEventListener('click', () => {
console.log('👍', 'butInstall-clicked');
const promptEvent = window.deferredPrompt;
if (!promptEvent) {
// The deferred prompt isn't available.
return;
}
// Show the install prompt.
promptEvent.prompt();
// Log the result
promptEvent.userChoice.then((result) => {
console.log('👍', 'userChoice', result);
// Reset the deferred prompt variable, since
// prompt() can only be called once.
window.deferredPrompt = null;
});
});
window.addEventListener('appinstalled', (event) => {
console.log('👍', 'appinstalled', event);
});
</script>
It comes from here https://web.dev/codelab-make-installable/
Here is a screenshot of the before install prompt event with the lighthouse report if it can help (by the way the plus sign in the url shows it's working):
console log infos
But on mobile the plus sign doesn't show up and nothing happens when I click the button... And as I don't have acces to the console I can't see any errors...
------ Edit ------
After using alert to log what the console says, I think the problem comes from the service worker does register well because I get this :
"ServiceWorker registration failed: SecurityError: Failed to register a ServiceWorker for scope ('https://192.168.1.26/') with script ('https://192.168.1.26/sw.js'): An SSL certificate error occurred when fetching the script.".
Is there a way to make the browser trust my self-singed certificate ?
Any help, suggestion or comment is welcome ^^
Its a .webmanifest and you dont match the criteria. You need an 512x512 AND an 192x192 icon.
As start_url i would just use /?source=pwa
"icons": [
{
"src": "icon.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "big_icon.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": "/?source=pwa",
After that you need to link your webmanifest with <link>
<link rel="manifest" href="/manifest.webmanifest">
Check if the paths are all correct.
Here is my own little "library" to abstract things: https://github.com/ilijanovic/serviceHelper (its under development tho)
If you met all criteria, then you can make your app installable
Here its how it works with my library. You instantiate the class and pass the path to the service worker.
var sh = new ServiceHelper("./sw.js");
sh.init().then(response => {
console.log("Initialized");
})
sh.on("notinstalled", (e) => {
console.log("App is not installed");
//do some stuff. For example enable some button
//button.classList.remove("disabled");
})
butInstall.addEventListener('click', () => {
sh.installApp().then(e => {
// e = user choice event
console.log(e);
}).catch(err => {
// error if the app is already installed
console.log(err);
})

Receiving Error in Chrome Extension: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist

I'm trying to create a very simple Chrome extension that will allow me to highlight a word on a webpage, right click to open the context menu, and then search it on a database called Whitaker's Words by simply appending the word to the search URL. I'm continuing to receive
"Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist."
as an error every time I run the code and attempt to use the context menu.
At the moment, I have already taken the steps to disable all other extensions and I attempted to use the port documentation on the Chrome Messaging Docs but I wasn't able to resolve the issue that way.
background.js
chrome.contextMenus.create({
title: "Search Whitaker's Words",
contexts: ["selection"]
});
chrome.contextMenus.onClicked.addListener(function() {
chrome.runtime.sendMessage({ method: "getSelection" }, function (response) {
sendToWW(response.data);
});
});
function sendToWW(selectedText) {
var serviceCall = 'http://archives.nd.edu/cgi-bin/wordz.pl?keyword=' + selectedText;
chrome.tabs.create({ url: serviceCall });
}
Here, I create a context menu and when the menu item is clicked, I send a message to the context script asking for the highlighted selection. I then return this to another function in background.js that will create a new tab with the search query.
content.js
chrome.runtime.onMessage.addListener(function (message) {
if (message.method === "getSelection"){
var word = window.getSelection().toString().trim();
console.log(word);
chrome.runtime.sendMessage({ data: word });
}
else
chrome.runtime.sendMessage({}); // snub them.
});
I listen here for the message and then take a selection from the window, trim, and send it back.
manifest.json
{
"manifest_version": 2,
"name": "Latinate",
"version": "0.1",
"description": "Aid in Latin translation using Whitaker's Words",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"jquery-3.4.1.min.js",
"content.js"
]
}
],
"background": {
"scripts": [
"background.js"
]
},
"permissions": [
"contextMenus",
"tabs"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
Any and all help would be appreciated! I've tried nearly everything I could find that seemed to apply.
The error message says there is no message listener on the other side. And indeed there is none because a message listener is a function registered with chrome.runtime.onMessage.addListener - in your extension only the content script has such a listener.
Instead of sending a new message back, send the response using sendResponse function which is passed as a parameter to the onMessage listener
(see also the messaging tutorial).
Another problem is that to send a message to a tab you need to use a different method: chrome.tabs.sendMessage with a tab id as the first parameter.
background script:
chrome.contextMenus.onClicked.addListener((info, tab) => {
chrome.tabs.sendMessage(tab.id, {method: 'getSelection'}, response => {
sendToWW(response.data);
});
});
content script:
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.method === 'getSelection') {
var word = window.getSelection().toString().trim();
console.log(word);
sendResponse({ data: word });
} else {
sendResponse({});
}
});

Open new tab with chrome extension an inject css with jQuery

I use a chrome extension with a popup to inject a website and hide some divs.
The problem now is, I want to open a new tab with the
url: https://app.example.de/dashboard/ and inject the style with my contentscript.js
Another problem is: Sometimes the application reloads the page. After this, all injections are lost. Is there any chance to inject allways the https://app.example.de/dashboard/ without click on the popup.html-Button?
The following code works fine, if the page is already open.
manifest.json
{
"name": "example stealth mode",
"version": "1.1",
"description": "lorem ipsum",
"browser_action": {
"default_icon": "icon-on.png",
"default_popup": "popup.html",
"default_title": "example stealth mode"
},
"manifest_version": 2,
"content_scripts": [
{
"matches": ["https://*.app.example.de/*"],
"js": ["jquery-1.11.0.min.js", "background.js"]
}
],
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs", "https://*.app.example.de/*"
]
}
popup.js
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('On').addEventListener('click', clickHandlerOn);
})
// An
function clickHandlerOn(e) {
chrome.extension.sendMessage({directive: "popup-click"}, function(response) {
this.close(); // close the popup when the background finishes processing request
});
}
background.js
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
switch (request.directive) {
case "popup-click":
// execute the content script
chrome.tabs.executeScript(null, { // defaults to the current tab
file: "contentscript.js", // script to inject into page and run in sandbox
allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0.
});
sendResponse({}); // sending back empty response to sender
break;
default:
// helps debug when request directive doesn't match
alert("Unmatched request of '" + request + "' from script to background.js from " + sender);
}
}
);
contenscript
$(document).ready(function() {
$('div#hlXXXContent').hide();
$('#hlYYY').hide();
$('#hlZZZ').hide();
$('h3.hlVVV').append(' Stealth Mode');
});
popup.html
<li><button class="hl123" id="On"><span class="hlSubmenuSelected">Stealthmode on</span</button></li>
The filename contentscript.js is odd because it's not a content script as you're using it. Why don't you try experimenting with run_at and have something load on each target page load, and that'll be your opportunity for your code to decide whether to do more things to the page.

Getting 'Proxy authentication required' when doing XMLHttpRequest (cross-origin) on Chrome Extension background page script

Question
I am getting a Error 407 'Proxy authentication required' when doing a cross-origin XMLHttpRequest from the background page of my Google Chrome extension.
I have Chrome set to use a HTTP Proxy which requires a username and password (Basic Auth).
The code below works if I do not have a proxy set in Chrome (as expected).
When I first open Chrome it asks for my proxy credentials, which I enter, and it remembers for the rest of the session.
I am assuming that the extension is in its own process and therefore does not have the credentials to the proxy stored.
My question is, is there any way around this? Is there a way to make the XMLHttpRequest work in the extension's background page script no matter what the proxy settings are set to in Chrome browser?
I am launching chrome with chrome.exe --proxy-server=my.proxy.server:3128 on Windows if that is relevant.
Example Code
manifest.json
{
[...]
"background_page": "background.html",
"permissions": [
"http://example.org/",
"http://mysite.com/"
],
"content_scripts": [
{
"matches": [
"http://example.org/*"
],
"js": ["contentscript.js"]
}
]
}
background.html->background.js:
function getById(request, sender, sendResponse) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
sendResponse(JSON.parse(xhr.responseText));
}
else {
// xhr.status == 407 here
sendResponse(null);
}
}
}
var url = 'http://mysite.com/script.php?id=' + request.id;
xhr.open('GET', url, true);
xhr.send();
}
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if ( request.action == 'getById' ) {
getById(request, sender, sendResponse);
}
else {
sendResponse(null);
}
});
contentscript.js:
chrome.extension.sendRequest({
'action': 'getById',
'id': 42
}, function(response) {
alert(response)
});