How to debug Google Chrome background script? [duplicate] - javascript

This question already has answers here:
Accessing console and devtools of extension's background.js
(9 answers)
Closed 7 years ago.
I have very simple extension:
manifest.json
{
"name": "historyCleaner",
"version": "0.1.1",
"manifest_version": 1,
"description": "This is my first Chrome extension",
"background": {
"scripts": ["cleaner.js"]
},
"permissions": [
"history"
]
}
cleaner.js
chrome.history.onVisited.addListener(function(HistoryItem result) {
console.log("it works!");
alert("it works!");
});
I've loaded it in Google Chrome, it is turned on and... it doesn't work. It doesn't log anything in console, it doesn't alert anything and what is worse, I can't find it in developers tools "Scripts" tab. How can I find why it doesn't work?
//edit
I've changed manifest.json to this one:
{
"name": "historyCleaner",
"version": "0.1.5",
"manifest_version": 1,
"description": "This is my first Chrome extension",
"background_page": "background.html",
"permissions": [
"history",
"background"
]
}
And embeded JavaScript in background.html

and also if your console.log("it works!"); does not show up, then that's mean chrome.history.onVisited is not fired yet.
ps: For function(HistoryItem result), you may want to change it to function(result).

This response might be late but would help the rest. if your background.html has javascript errors then the page will not load (to inspect).
To find out whats wrong with your background.html, under chrome://chrome/extensions/ (i.e., manage extensions), click on the background.html link. This will load the developer tools but without background.html. At the botton-right of the window, you will see a red error symbol, and clicking on it will provide line numbers that needs to be fixed.

Related

Firefox Extension / Webextensions: Why doesn't the MDN example of Connection Based Messaging work?

This is the first time I read about writing Firefox extensions.
What I need is obviously only viable via WebExtensions and both a background and a contentscript. I actually only want to write all open tabs as links in a new tab and then File->Save it. Another alternative Idea was to put it into a JSON Object and save that through a dialog, then I probably could even spare the contentscript but I haven't found anything in the API to download a JSON Object via asking the user to download it via Download Dialog.
Whatever. I think I need to communicate with the content-script then.
I tried to run the following example, but it is not working. When I load the manifest file and open the debugger for extensions, it doesn't log anything and nothing has happened except that the variables myPort and portFromCS seem to be declared without any value.
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#connection-based_messaging
// manifest.json
{
"manifest_version": 2,
"name": "Save Open Tabs",
"version": "1.0",
"description": "Save my tabs",
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["content.js"]
}
],
"permissions": [
"activeTab",
"tabs"
]
}
// content.js
let myPort=browser.runtime.connect({name:"port-from-cs"});
myPort.postMessage({greeting: "hello from content script"});
myPort.onMessage.addListener((m) => {
console.log("In content script, received message from background script: ");
console.log(m.greeting);
});
// background.js
let portFromCS;
function connected(p) {
portFromCS = p;
portFromCS.postMessage({greeting: "hi there content script!"});
portFromCS.onMessage.addListener((m) => {
portFromCS.postMessage({greeting: "In background script, received message from content script:" + m.greeting});
});
}
browser.runtime.onConnect.addListener(connected);
Why doesn't the example work? Maybe wrong URL matching in the manifest file?

How to know whether turn on sync in chrome browser is enabled using javascript

I am trying to check below point for my assignment programatically
1. check if turn on sync is enabled in chrome
EDIT:
So far i have developed a chrome extension and trying to get the chrome.storage.sync object
But i am unable to get the status of the turn on sync "whether synced or no"
Below is my manifest.json
{
"name": "Check Turn on sync",
"version": "1.0",
"description": "Build an Extension!",
"permissions": ["storage"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"manifest_version": 2
}
I have provided a background.js file
is there a way in chrome.storage.sync that provides status of the sync
I am going to answer my own question, as i was able to find the answer.
I was able to get the status of sync is turned on or no along with the email ids. Here is the code :
create a manifest.json file with below content
{
"name": "Test turn on sync",
"version": "1.0",
"description": "Extension",
"permissions":[
"identity",
"identity.email"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"manifest_version": 2
}
Create a background.js file in the same folder
chrome.identity.getProfileUserInfo(function(data) {
if (data.id) {
alert(data);
}
else
{
alert("User has not turned on sync");
}
});
Add the folder as chrome extension Run the extension from chrome with the help of identity.email in permissions, you will be able to get even the email-id of the user who has turned on sync, along with status.

Content script not listening to message event

I am developing my first browser extension for my website.
What this extension should basically do is to have a browser action which opens a pop-up where you can edit specific cookie values for the current page.
However, cookie A can exist on the page / while cookie B can exist on the page /checkout. So I don't want to list every cookie inside the pop-up, only the one which is active on the current page.
So, I searched the documentation and found that in order to communicate between web page and add-on you have to use the message system as described here
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#Communicating_with_the_web_page
To do so, my website has a JavaScript file which is loaded on every page. In this JavaScript I'm executing the following code
window.postMessage({type: 'FROM_PAGE', data: visibleCookies}, '*');
This piece of code is definitely executed, because I put a console.log before or after that statement, I can see that it's being logged.
Now, in my content script I want to listen to this by executing the following code
// experimentManager.js
console.log('testd');
window.addEventListener('message', (event) => {
console.log(event);
if (event.source !== window) {
return;
}
});
However, the console.log(event); is never executed. The listener is never activated. When I press the browser action so that the popup opens testd is logged into console, but still, the listener doesn't get any events. It's just not getting executed.
I don't know which files are relevant, but this is my manifest.json
// manifest.json
{
"manifest_version": 2,
"name": "My first addon",
"version": "1.0",
"description": "My first addon description",
"icons": {
"48": "icons/icon.png"
},
"browser_action": {
"default_icon": "icons/icon.png",
"default_title": "My first addon",
"default_popup": "popup/manage_experiment.html",
"browser_style": true
},
"permissions": [
"tabs",
"cookies",
"<all_urls>"
],
"content_scripts": [
{
"matches": ["*://*.mydomain/*"],
"js": ["experimentManager.js"]
}
]
}
And inside the pop-up script I'm executing this code among other things
browser.tabs.executeScript({file: "/content_scripts/experimentManager.js"})
.then(manageExperiments)
.catch(handleError);
which is probably the reason why the console.log('testd') gets executed, but nothing else?
What am I missing?

Creating Chrome Extension to Dismiss Notifications via Keyboard Shortcut

I'm new to Chrome extension development. I am currently looking to make a Chrome extension to dismiss notifications. I want the extension to be activated once via shortcut keys.
Before looking at the code below, I want to let it be known that the alert does show up... but the Chrome Extensions page shows the error:
"Error in event handler for commands.onCommand: TypeError: Cannot read property 'getAll' of undefined"
on the line:
chrome.notifications.getAll((items) => {
The chrome.notifications object is somehow undefined, so it seems that Chrome thinks that there are no current notifications being displayed...which is strange because there indeed are, as the image shows.
Would anyone please help by shedding some light on this situation?
manifest.json:
{
"name": "ClearAll",
"version": "1.0",
"description": "Clear notifications!",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"commands": {
"clear": {
"suggested_key":{
"default": "Alt+Shift+S"
},
"description": "Executes clear"
}
},
"manifest_version": 2
}
background.js:
chrome.commands.onCommand.addListener(function(command) {
if (command == 'clear') {
alert("testing");
chrome.notifications.getAll((items) => {
if (items)
for (let key in items)
chrome.notifications.clear(key);
});
}
});
Error:
You might already have figured this out, but for anyone who stumbles upon this question in the future: it's not possible to write an extension that dismisses all notifications on Chrome because it is not possible for any extension to get access to a user's browser-wide notifications; the notifications permission in the manifest.json lets you create and clear notifications created by your extension. Indeed, it would be a privacy violation if any extension was allowed to do this!
From https://developer.chrome.com/apps/notifications#method-getAll,
Retrieves all the notifications of this app or extension (emphasis mine.)
You need to add the notifications permission to your manifest
{
"name": "ClearAll",
"permissions": ["notifications"],
.......
}

Javascript onbeforerequest redirect url does not work

I was trying to create a Mozilla Firefox URL redirection addon however when I created it myself using the code on the mozilla firefox page about OnBeforeRequest url redirection, the addon didn't work. So I decided to copy and paste the code from the Mozilla website guide to see if I wrote the code wrong, however the same thing happens. It cancels the requests correctly however whenever I try redirecting urls using the redirectUrl option, it doesn't work
My code is as follows:
manifest.json
{
"description": "Demonstrating webRequests",
"manifest_version": 2,
"name": "webRequest-demo",
"version": "1.0",
"applications": {
"gecko": {
"id": "#addontest"
}
},
"permissions": [
"webRequest", "webRequestBlocking"
],
"background": {
"scripts": ["main.js"]
}
}
main.js
var pattern = "https://mdn.mozillademos.org/*";
function redirect(requestDetails) {
console.log("Redirecting: " + requestDetails.url);
return {
redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"
// cancel:true
};
}
browser.webRequest.onBeforeRequest.addListener(
redirect,
{urls:[pattern], types:["image"]},
["blocking"]
);
In the main.js, if I were to comment out the
redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"
and uncomment the following line:
cancel:true
the code works correctly and the requests are canceled, however its just whenever I try to redirect it, it stops working.
Can anyone help please? It's been bugging me for a few days now and I just can't seem to find anything to fix it. There's no errors or anything in the firefox console (CTRL + SHIFT + J) or in the firebug console

Categories

Resources