Chrome extension: context menu icon not showing - javascript

I am building a Chrome extension and I set up a context menu which will show up and check the items (images or text) that the user selects from a table in the extension's popup.
This is my code for creating the context menu in popup.js's window.onload:
chrome.contextMenus.removeAll();
chrome.contextMenus.create( {title: "Toggle Selected",
documentUrlPatterns: [ "chrome-extension://*/popup.html"],
contexts:["selection"], onclick: toggleselected} );
This is the function that gets called on the context menu's onclick - also in popup.js (simplified version):
function toggleselected(info, tab)
{
var selection = window.getSelection(),
q0 = document.querySelectorAll("[id^='id0']"),
q1 = document.querySelectorAll("[id^='id1']");
for (var i = 0; i < somearray.length; i++)
{
if (selection.containsNode(q1[i], true))
{
somearray[i].checked = !somearray[i].checked;
q0[i].checked = !q0[i].checked;
}
}
updatesomearrayinfo();
}
And this is my manifest.json file (again, simplified version):
{
"manifest_version": 2,
"name": "Extension Name",
"version": "1.0",
"description": "Random description",
"browser_action":
{
"default_icon":
{
"16": "icon16.png",
"32": "icon32.png",
"48": "icon48.png",
"128": "icon128.png"
},
"default_popup": "popup.html"
},
"background":
{
"scripts": ["somescript.js"],
"persistent": true
},
"permissions": ["contextMenus", "tabs", "downloads", "<all_urls>"]
}
Everything works fine and the context menu correctly shows up when needed ... except that it doesn't have the extension's own icon next to it, but the default Chrome extension icon (the grey one). What can be done to correct this behavior? The icons in my manifest are ok, one of them (the 16x16 pixels, I believe) is correctly shown on my extension button, and apart from others usually doing the whole context menu thing from event pages, using chrome.runtime.onInstalled, contextMenus.onClicked.addListener and other listeners (which I am reluctant to use, since I specifically need to work with the variables from popup.js - e.g. somearray and queries on popup's elements), I don't seem to be doing anything different than things done by other extensions or the code samples in the answers here on StackOverflow. And they all get their own extension icons shown, apparently without doing anything special.
EDIT: Also, does anyone knows why the context menu for a selection is triggered only when the selection contains more than one specific item (an image, in my case)?

Related

Chrome Extension Is not saving the value in local storage

I'm trying to build my own custom made dark mode theme in Javascript, it is a chrome extension. It is almost finished, the click handler is working just fine, it makes the website darker and vice versa. However, I want it to save the value so if I turn the webpage darker, I want it to be dark even after I refresh the page, or, open the same page again so it's still dark (I hope I make sense). At this point once I refresh the page it loses the value, so if dark mode is applied - it becomes white again (and if I open the same page it is white on the second tab). I'm attaching the screenshots, could anyone let me know what's wrong or what's causing the issue so I can finally finish the extension.
**chrome.storage.sync.set({ key: "dark" }, function () {
console.log("Value is set to " + "dark");
});
chrome.storage.sync.get(["key"], function (result) {
console.log("Value currently is " + result.key);
});
// localStorage.setItem("darkMode", 1);
})();
The manifest.json code:
{
"name": "chrome extension",
"description": "Go to dark mode from Light mode and vice versa",
"version": "1.0.0",
"manifest_version": 2,
"background": {
"scripts": ["popup.js"],
"persistent": true
},
"browser_action": {
"default_title": "PYL",
"default_popup": "popup.html"
},
"permissions": ["https://*/*", "http://*/*", "tabs", "storage", "activeTab"]
}**

Chrome Extensions - Click on element in actual page [duplicate]

This question already has answers here:
How to access the webpage DOM/HTML from an extension popup or background script?
(2 answers)
Closed 6 years ago.
I'm trying to make a simple extension, that can click in a element on the my principal page, example: I have a login page that have 6 buttons to choose a password and I want to simulate a click in each button(I already did this on Selenium).
But, when I use de DOM(document object) the chrome is getting the document from a new HTML and is not getting my HTML.
Above my example:
background.js
function checkForValidUrl(tabId, changeInfo, tab) {
chrome.pageAction.show(tabId);
}
function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
chrome.tabs.onUpdated.addListener(checkForValidUrl);
chrome.pageAction.onClicked.addListener(function(tab) {
var element = getElementByXpath("//label[contains(text(),'1')]");
element.click();
});
On my code, when I try to select a Element I can't get the main page.
MANIFEST.js
{
// Required
"manifest_version": 2,
"name": "Minha Extensão",
"version": "2",
// Recommended
"description": "A plain text description",
"icons": { "16": "icon-w-1.png",
"48": "icon-w-2.png",
"128": "icon-w-3.png" },
"background": {
"scripts": ["background.js"]
},
"page_action": {
"default_icon": "icon-w-3.png"
},
"permissions": ["tabs", "http://*/*", "https://*/*"]
}
My next step will be, in the moment that I click on the extension button, open a new window with buttons that when I click, can simulate a click on another button in the main page.
You can't access web page DOM from background page. You have to insert content script.
See more in - Chrome documentation

How to open a popup window from an extension

I have a working extension that allows me to check market prices of steam items.
You basically click the extension and then a prompt box opens and the item is inputted there.
It then opens up a new windows with the search query, displaying the market prices.
I would like to tweak it by displaying the list of items as a popup from the extension, like the default popup.
For that I need to know some stuff:
1) How do I call that popup function within the js code?
2) How do I open it so that it shows only what I need? like this, instead of showing the whole site.
Here are the codes:
manifest:
"manifest_version": 2,
"name": "CS:GO checker",
"description": "This extension checks market prices",
"version": "1.1337",
"permissions": [
"http://steamcommunity.com/market/"
],
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["popup.js"],
"persistent": false
}
popup.js:
function test ()
{
var userInput=prompt("Please enter your item below:");
if (userInput!=null)
{
newwindow=window.open("http://steamcommunity.com/market/search?q="+userInput,userInput,'height=800,width=670');
if (window.focus) {newwindow.focus()}
return false;
}
}
chrome.browserAction.onClicked.addListener(test);
Thanks in advance!
edit: I forgot to mention that I'm very new to javascript, so if you have an answer, try to explain it very carefully to me that I could understand.

Making my browser action act as an on/off switch (with appropriate icons)

I'm working on a Google Chrome extension, and I essentially want the browser action to act as an on/off switch. Whenever it is "on", it will have a certain icon and the script is executed on the page. Whenever it is "off", it has a certain icon and the script is not executed.
Here's my manifest.json:
{
"manifest_version": 2,
"name": "Resource Control",
"description": "Controls what resources load from a website.",
"version": "1.0",
"icons": {
"16": "locked_16.png",
"48": "locked_48.png",
"128": "locked_128.png"
},
"browser_action": {
"default_icon": "locked_16_off.png" //icon is "off" by default
},
"background": {
"scripts": ["main.js"]
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
]
}
And here's main.js:
var toggled = false;
chrome.browserAction.onClicked.addListener(function(tab) {
toggled = !toggled;
if(toggled){
chrome.browserAction.setIcon({path: "locked_16_on.png", tabId:tab.id});
chrome.tabs.executeScript(null,{code:"document.body.style.backgroundColor='red'"});
}
else{
chrome.browserAction.setIcon({path: "locked_16_off.png", tabId:tab.id});
chrome.tabs.executeScript(tab.id, {code:"alert()"});
}
});
if (toggled) {
chrome.tabs.executeScript(null,{code:"document.body.style.backgroundColor='red'"});
}
Right now I'm just working on getting this functionality working before moving on, so to test I'm just setting the page's background to red. However, whenever I load a new webpage, the icon is reverted back to the "off" icon even though the extension is still "on", and the script isn't injected into the new page. Can someone help me find where I'm going wrong?
When you pass a tabId to chrome.browserAction.setIcon it only sets the icon for when that specific tab is active. If you switch to a different tab, the icon will revert to the default.
You are only running chrome.tabs.executeScript when the browserAction is clicked on. If want code injected on every page you either need to use a content script that is injected on all tabs or listen for new tabs getting created and executeScript every time.

Chrome Extension - executeScript not in active tab

I'm trying a simple Chrome Extension example which should enable me change the background color of any open youtube tabs to red. What I've noticed is that the background of the page is only turned red if I'm on the actual page i.e. it is the active tab.
Code:
function getYouTubeTabs() {
queryInfo = {
'url': '*://www.youtube.com/*'
};
chrome.tabs.query(queryInfo, function (result) {
for (i = 0; i < result.length; i++) {
chrome.tabs.executeScript(result[i].id, {
code: 'document.body.style.backgroundColor="red"'
});
}
});
}
This is the code I have, I might be missing something. Not sure if executeScript could be used on 'non-active' tabs. Thanks in advance.
EDIT
manifest.json
{
"manifest_version": 2,
"name": "First menu item",
"description": "Testing Context Menus",
"version": "1.0",
"permissions": [
"contextMenus", "tabs", "activeTab"
],
"icons": {
"16": "myicon.png",
"128": "myicon2.png"
},
"background": {
"scripts": ["background.js"]
}
}
The activeTab permission, allows you to call tabs.executeScript or tabs.insertCSS on that tab.
On the contrary, in order to be able to programmatically inject code into an non-active tab, besides the tabs permission, your extension must have cross-origin permissions for the page.
So, you need to modify your manifest's permissions section like this:
"permissions": [
...
"*://www.youtube.com/*"
],
Adding "persistent": false in the background section should work fine as well (and is the preferred way).

Categories