It is possible if method SetBadgeText don't lose counting numbers? What I am struggling is, when I click on a button and counter start to count numbers after that I'm going to check some other pages, sometimes counting starts from zero, the same thing is when I want to close chrome and open it again. How this is possible to save your actual setBadgeText number in memory and start from latest one without losing it?
background.js
var counter = 0;
chrome.runtime.onMessage.addListener(message => {
if(message === 'clicked') {
counter += 1;
chrome.browserAction.setBadgeText({
text: counter.toString()
});
}
});
content-script.js
document.body.addEventListener('click', e => {
if(e.target.matches('[value="Google Search"]')) {
chrome.runtime.sendMessage('clicked')
}
});
manifest.json
{
"manifest_version": 2,
"name": "Counter",
"version": "1.0",
"content_scripts": [
{
"matches": ["https://*/*"],
"run_at": "document_end",
"js": ["content-script.js"]
}
],
"description": "description",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"browser_action": {
"default_title": "counter"
}
}
Use the storage API: https://developer.chrome.com/apps/storage
The "sync" storage is synced to any Chrome browser you're logged into. The "local" storage is, uh, local.
Here's how you might integrate the storage API into your example:
// background.js
chrome.runtime.onMessage.addListener(message => {
if(message === 'clicked') {
chrome.storage.local.get('counter', ({counter}) => {
counter += 1;
chrome.browserAction.setBadgeText({
text: counter.toString()
});
chrome.storage.local.set('counter', counter)
})
}
});
You will also need to add the "storage" permission to your manifest:
// manifest.json
{
...
"browser_action": {
"default_title": "counter"
},
permissions: [
"storage"
]
}
Related
I'm trying to build an extension to monitor the xhr portion of the devtools network tab. With some help , I have been able to get the requests to be displayed on the service-worker console and I can log the Post requests. I'm also now saving the data "point" in chrome.storage. My next step is to read the data from chrome.storage.local, and have the content script log it to the console. However although I am getting no errors, I don't see any output in the console. No errors seen though. What am I doing wrong?
manifest.json:
{
"manifest_version": 3,
"version": "1.0",
"name": "Hello World!",
"description": "Learning how to make a chrome extension!",
"icons": {
"16": "images/puppy16.png",
"48": "images/puppy48.png",
"128": "images/puppy128.png"
},
"action": {
"default_icon": "images/puppy.png",
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js"
},
"host_permissions": ["*://*.cnn.com/"],
"permissions": ["webRequest", "activeTab","tabs"],
"content_scripts": [
{
"matches": ["*://cnn.com/*"],
"js": ["popup.js"]
}
]
}
In my background.js:
(function () {
var point;
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
// Use this to decode the body of your post
const postedString = decodeURIComponent(String.fromCharCode.apply(null,
new Uint8Array(details.requestBody.raw[0].bytes)));
console.log(postedString)
const body = JSON.parse(postedString);
point = body.CenterPoint.Point;
console.log(point);
chrome.storage.local.set({ 'key': point }, function () {
console.log('Value is set to ' + point);
});
},
{ urls: [url] },
["requestBody"]
);
})();
popup.js:
chrome.storage.onChanged.addListener(function (changes, namespace) {
for (let [key, { oldValue, newValue }] of Object.entries(changes)) {
console.log(
`Storage key "${key}" in namespace "${namespace}" changed.`,
`Old value was "${oldValue}", new value is "${newValue}".`
);
}
});
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()
}
})
manifest.json
{
"manifest_version": 2,
"name": "Project",
"description": "Chrome Extension for sending messages",
"version": "1.0",
"browser_action": {
"default_icon": "red_dot.png"
},
"permissions": [
"activeTab",
"https://ajax.googleapis.com/",
"storage"
],
"background" : {
"scripts" : ["background.js"]
},
"content_scripts": [
{
"matches":["https://www.website.com/*"],
"js":["keypress.js", "jquery.js", "js_file.js"],
"run_at": "document_end"
}
]
}
background.js
var running = false
chrome.browserAction.onClicked.addListener(function(tab) {
if (running) {
alert('script is running, turning off');
chrome.browserAction.setIcon({path: "red_dot.png"})
running = false
} else {
alert('script is not running, turning on');
chrome.browserAction.setIcon({path: "green_dot.jpg"})
running = true
}
});
When I click on the icon, I get the popup as expected, but the icon itself isn't changing.
I'm getting this error:
Unchecked runtime.lastError: Icon invalid.
but I don't understand why. The code seems valid.
use this api and carefully enter params specifically path
https://developer.chrome.com/extensions/browserAction#method-setIcon
I am making a chrome extension it will get me to certain page by autoclicking. Since it goes from page to page. I am not able to get past after the first page. I am not able to do when the second page loads after first click
manifest.json
{
"manifest_version": 2,
"name": "AutoClick",
"description": "This autoclicks",
"version": "1.1",
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"content_scripts": [{
"matches": ["*://*.blogger.com/*"],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": false
}],
"permissions": [
"activeTab",
"tabs",
"*://*.blogger.com/*"
]
}
background.js
chrome.tabs.create
chrome.browserAction.onClicked.addListener(function (tab) {
var newURL = "https://draft.blogger.com/blog/posts/3778735982367012067";
chrome.tabs.create({ url: newURL });
chrome.tabs.executeScript({ file: "content.js" });
});
content.js
function createpost(){
document.querySelector('.CwaK9').click()
}
function video1(){
document.querySelector('.vde74d').click()
}
if (window.location.href == "https://draft.blogger.com/blog/posts/3778735982367012067") {
createpost()
newFunction()
}
function newFunction() {
if (window.location.href.match('https://draft.blogger.com/blog/posts/3778735982367012067/')) {
video1();
}
}
using match because it add random ID to end of the URL after first click.
It works fine during first click but when the next page loads it don't.
I have a website that updates automatically when I get a message and sends me a push notification. I am trying to create a chrome extension that can detect when I get that push notification and do something when it happens.
This is what I have so far but it doesn't seem to be outputting to console. Is something wrong or do I need to change something about my manifest?
inject.js
self.addEventListener('push', function(event) {
//I want to do a thing here
if (event.data) {
console.log('This push event has data: ', event.data.text());
} else {
console.log('This push event has no data.');
}
});
manifest.json
{
"name": "Push notifcation detector",
"version": "1.0",
"description": "Do a thing!",
"manifest_version": 2,
"permissions": [
],
"content_scripts": [
{
"matches": [
"https://mywebsite.com/*"
],
"js": [
"./js/inject.js"
],
"all_frames": false,
"run_at": "document_end"
}
],
"web_accessible_resources": [
"images/**/*.png"
],
"browser_action": {
"default_icon": {
"16": "./images/icons/icon.png",
"48": "./images/icons/icon.png"
}
},
"icons": {
"16": "./images/icons/icon.png",
"48": "./images/icons/icon.png",
"128": "./images/icons/icon.png"
}
}
Thanks for any help you can give me!
It looks like you need to run some sort of background page to receive the message. For the dropdowns, as far as I know, Chrome creates and drops the pages when you select and de-select, or when the browser is on the configured page. By default, it's not going to work because the page isn't running constantly.
This may help: https://developer.chrome.com/extensions/background_pages