Chrome Extension - executeScript not in active tab - javascript

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).

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 extension: context menu icon not showing

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)?

Run the script only onclick on chrome extension

Whenever my chrome extension icon is clicked, I want to run a script that would make certain changes to the current webpage.
I have tried using content_scripts in my manifest and it worked but the problem is , the script runs even if I did not clicked on the icon.
I have found that, I need to use background script.In my background.js file I have added
chrome.browserAction.onClicked.addListener(function(tab) {
alert();
});
and it is not working.
Here is my manifest file.
{
"manifest_version": 2,
"name": "Reveal Password",
"description": "Reveals password in password input field",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
}
}
Plus I want to execute the script that I made that manipulates the current web page too.
Use chrome.tabs.executeScript() to execute code in a tab like this:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
code: 'alert("Hello")'
});
});
Instead of code, you could also use a file which contains the code :
chrome.tabs.executeScript(null, {file: "content_script.js"});
NOTE : You need activeTab permissions to execute code in an active tab
"permissions": [
"activeTab"
]

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 get UI element from background script

I am starting to develop a chrome extension.
In my case I have the following manifest.json:
{
"name": "mY Notifier",
"version": "1.0",
"manifest_version": 2,
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": [
"myscript.js"
],
"persistent": false
},
"permissions": [
"tabs","alarms"
]
}
So, as you can see i have a default popup html page and a background script.
I need a Background script because I need to update the icon badge from time to time when the Extension is enabled (not just if the user clicks on the icon). This works fine.
In my popup.html i have a couple of checkboxes. Now in my background script i want to check which of the checkboxes are enabled. How can i do this? I cannot refer to my ui elements in popup.html using elementById. How can this be done?
You can't access to popup.html from myscript.js because popup.html don't loaded before the click on a button.
You can call functon of myscript.js from popup.html:
popup.js code:
var bg = chrome.extension.getBackgroundPage();
bg.someFunction(stateOfCkeckboxes);

Categories