Chrome extension - cookies.getAll returns nothing - javascript

When I run the following function I get a zero for the cookie length:
function cookieinfo() {
chrome.cookies.getAll({}, function(cookie) {
console.log(cookie.length);
allCookieInfo = "";
for (i = 0; i < cookie.length; i++) {
console.log(JSON.stringify(cookie[i]));
allCookieInfo = allCookieInfo + JSON.stringify(cookie[i]);
}
localStorage.allCookieInfo = allCookieInfo;
});
It should be finding all the cookies the user has but I'm getting nothing.
Use: I'm creating a chrome extension that creates a new tab for the user. I'm trying to recreate chromes new tab look and how they display the pages the users already visited.
Here is the manifest.json:
{
"manifest_version": 2,
"name": "-------",
"version": "0.1",
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": [
"<all_urls>"
],
"js": ["jquery-3.2.1.min.js", "content.js"]
}],
"permissions": ["tabs", "cookies"],
"chrome_url_overrides": {
"newtab": "NewTab.html"
}
}

According to chrome dev docs, "To use the cookies API, you must declare the "cookies" permission in your manifest, along with host permissions for any hosts whose cookies you want to access."
So you need to add "host permissions" in manifest.json like this example

Related

How to activate/deactivate chrome extension with keyboard shortcut (development)

I'm trying to set a keyboard shortcut to active/deactivate my Chrome extension that I'm developing. The Chrome extension just consists of a "content_script" that runs on certain sites. I want it to fully activate/deactivate the extension, like if I were to disable it via Chrome://extensions.
In my search for answers, I saw a lot of suggestions to add "_execute_browser_action" to my manifest.json, but I think this command requires a listener that needs to be set up in background.js (correct me if I'm wrong). I want to avoid a background.js if possible, as I want to keep this extension short and sweet.
Here is my manifest.json:
{
"manifest_version": 2,
"name": "foo",
"description": "foo",
"version": "0.1.0",
"commands": {
"_execute_browser_action": {
"suggested_key": {
"default": "Ctrl+Shift+8"
}
}
},
"content_scripts": [{
"js": ["./dist/bundle.js"],
"matches": [ ...certain sites... ]
}],
"icons": {
"16": "/icons/logo16.png",
"32": "/icons/logo32.png",
"48": "/icons/logo48.png",
"128": "/icons/logo128.png"
}
}
With this manifest.json, the shortcut shows up in Chrome://extensions/shortcuts, but the shortcut does nothing. When I press the combination, nothing happens. Even when I refresh the page, reload extension, re-bundle, restart Chrome, etc.
How should I go about adding this keyboard shortcut?
Also, I'm using Babel/Webpack, if that helps.
I ended up solving my own issue. Updating here in case it helps anyone else.
It turns out a background.js was exactly what I was looking for. My background script sets a chrome.storage API field, triggered by browserAction, which my content_script then ingests to toggle it on/off. Then the page is refreshed to update the page html. (Inspiration taken from here)
background.js:
var x = true
enableBrowserAction()
function disableBrowserAction() {
chrome.storage.local.set({enabled: false})
}
function enableBrowserAction() {
chrome.storage.local.set({enabled: true})
}
function updateState() {
if (x == false) {
x = true
enableBrowserAction()
} else {
x = false
disableBrowserAction()
}
chrome.tabs.reload()
}
chrome.browserAction.onClicked.addListener(updateState)
manifest.json (with only the necessary fields):
{
"manifest_version": 2,
"browser_action": {},
"commands": {
"_execute_browser_action": {
"suggested_key": {
"default": "Ctrl+Shift+8"
}
}
},
"permissions": [
"storage"
],
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"js": ["./dist/bundle.js"],
"matches": [ ...certain sites... ]
}]
}
content_script (entry for bundle.js):
import ServiceHandler from './ServiceHandler.js'
chrome.storage.local.get('enabled', data => {
if (data.enabled) {
const sh = new ServiceHandler()
sh.execute()
}
})

Chrome extension webRequest.onBeforeRequest

I am trying to create an extension to analyse requests made on the chrome browser but I can't put it work. The alert never fires.
manifest.json
{
"name": "Test",
"description": "Test",
"version": "1.0",
"manifest_version": 2,
"permissions": ["background", "tabs", "webRequest", "webRequestBlocking", "*://*/*"],
"background": {
"scripts": ["background.js"],
"persistent": true
}
}
background.js
var callback = function(details) {
alert("hello");
};
var filter = { "*://*/*" };
var opt_extraInfoSpec = [];
chrome.webRequest.onBeforeRequest.addListener(
callback, filter, opt_extraInfoSpec);
Why is it my alert not firing?
Your filter is the wrong format - it's not a valid object at all. Addtionally it needs to contain at least the 'url' property. If you wan't all URL's, use this:
var filter = {urls: ["<all_urls>"]};
Check out this for exact details on the format for the filter: https://developer.chrome.com/extensions/webRequest#type-RequestFilter

Screenshot using chrome.tabs.captureVisibleTab

I'm trying to capture the visible area of a page using chrome.tabs.captureVisibleTab. Here is the code that makes the call:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.name == 'screenshot') {
chrome.tabs.captureVisibleTab(null, null, function(dataUrl) {
sendResponse({ screenshotUrl: dataUrl });
});
}
});
But when I try to capture the tab I get this error:
Unchecked runtime.lastError while running tabs.captureVisibleTab: The 'activeTab' permission is not in effect because this extension has not been in invoked.
Here is my manifest file:
{
"manifest_version": 2,
"name": "Empathy",
"version": "0.1",
"description": "Simulate accessibility issues for websites.",
"browser_action": {
"default_icon": "empathy19.png",
"default_title": "Empathy!"
},
"permissions": [
"activeTab",
"contextMenus",
"desktopCapture",
"tabCapture",
"tts" // Text-to-speech
],
"background": {
"scripts": [
"boot.js"
],
"persistent": false
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [
"src/helpers.js",
"src/colorblindness.js",
"lib/colorvision.js",
"lib/html2canvas.js"
]
}
]
}
I have active tab permissions
The call is being made from a background script
I'm matching <all_urls>
Why do I get that error?
There are things that talk about <all_urls> as something to match, but what I was missing was the <all_urls> permission. After I added the permission, it worked.

Selectively include javascript file dependent on website

I'm trying to build a Chrome Extension that will work with two websites, we'll call them website1.com and website2.com. Depending on what website we are on I would like to include a different JS file that will store all the logic (In this example I have called it code-for-website-1.js (there would also be another JS for website2.com).
I'm having a problem figuring out how I can only include code-for-website-1.js when I am on website1.com and code-for-website-2.js when I am on code-for-website-2.js.
Here is my manifest:
{
"name": "My Chrome Extension",
"version": "1.0",
"description": "Extension description",
"manifest_version": 2,
"permissions": ["tabs", "http://www.website1.com", "http://www.website2.com"],
"content_scripts": [
{
"matches": ["http://www.website1.com"],
"js": ["jquery.js", "code-for-website-1.js"]
}
]
}
I tried to use one controller.js that would use the following command:
if (onWebsite1 == true){
chrome.tabs.executeScript(null, { file: "code-for-website-1.js" });
} else {
chrome.tabs.executeScript(null, { file: "code-for-website-2.js" });
}
With this I just get the error:
Uncaught TypeError: Cannot call method 'executeScript' of undefined
in the manifest according to the documentation you can add multiple objects to the content_script array
example
"content_scripts": [
{
"matches": ["http://www.website1.com/*"],
"js": ["script_for_website1.js"]
},
{
"matches":["http://www.website2.com/*"],
"js":["script_for_website2.js"]
}
]

Get selected text in a chrome extension

I wanna make an extension that takes the selected text and searches it in google translate
but I can't figure out how to get the selected text.
Here is my manifest.json
{
"manifest_version": 2,
"name": "Saeed Translate",
"version": "1",
"description": "Saeed Translate for Chrome",
"icons": {
"16": "icon.png"
},
"content_scripts": [ {
"all_frames": true,
"js": [ "content_script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_start"
} ],
"background": {
"scripts": ["background.js"]
},
"permissions": [
"contextMenus",
"background",
"tabs"
]
}
and my background.js file
var text = "http://translate.google.com/#auto/fa/";
function onRequest(request, sender, sendResponse) {
text = "http://translate.google.com/#auto/fa/";
text = text + request.action.toString();
sendResponse({});
};
chrome.extension.onRequest.addListener(onRequest);
chrome.contextMenus.onClicked.addListener(function(tab) {
chrome.tabs.create({url:text});
});
chrome.contextMenus.create({title:"Translate '%s'",contexts: ["selection"]});
and my content_script.js file
var sel = window.getSelection();
var selectedText = sel.toString();
chrome.extension.sendRequest({action: selectedText}, function(response) {
console.log('Start action sent');
});
How do I get the selected text?
You are making it a bit more complicated than it really is. You don't need to use a message between the content script and background page because the contextMenus.create method already can capture selected text. Try adjusting your creations script to something like:
chrome.contextMenus.create({title:"Translate '%s'",contexts: ["all"], "onclick": onRequest});
Then adjust your function to simply get the info.selectionText:
function onRequest(info, tab) {
var selection = info.selectionText;
//do something with the selection
};
Please note if you want to remotely access an external site like google translate you may need to adjust your permissions settings.
I would note - this is no longer valid response if you are moving to manifest version 3. Manifest version 3 adds the concept of "service workers". https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/
You have to update several things, but the basic concept is the same.
manifest.json
"name": "Name of Extension",
"version": "1.0",
"manifest_version": 3,
"description": "Description of Extension",
"permissions": [
"contextMenus",
"tabs",
"activeTab"
],
"background": {
"service_worker": "background.js",
"type": "module"
},
background.js
//Setting up the function to open the new tab
function newTab(info,tab)
{
const { menuItemId } = info
if (menuItemId === 'anyNameWillDo'){
chrome.tabs.create({
url: "http://translate.google.com/#auto/fa/" + info.selectionText.trim()
})}};
//create context menu options. the 'on click' command is no longer valid in manifest version 3
chrome.contextMenus.create({
title: "Title of Option",
id: "anyNameWillDo",
contexts: ["selection"]
});
//This tells the context menu what function to run when the option is selected
chrome.contextMenus.onClicked.addListener(newTab);

Categories

Resources