Can't shoot a response every time extension button is clicked - javascript

So I'm just trying to get a response every time the extension button is clicked. So like with AdBlock how this comes down
But instead I'm just trying to do a console.log() every time the button is clicked without any visible popups.
I've tried this so far
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
switch (request.directive) {
case "popup-click":
// execute the content script
chrome.tabs.executeScript(null, { // defaults to the current tab
file: "real.js", // script to inject into page and run in sandbox
allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0.
});
sendResponse({}); // sending back empty response to sender
break;
default:
// helps debug when request directive doesn't match
alert("Unmatched request of '" + request + "' from script to background.js from " + sender);
}
}
);
Then my real.js
console.log("Yo");
But sadly I only get a Yo when it launches. Any ideas?

If you don't have a popup (nothing shows when you click the button), then there is an event that will fire when the button is clicked:
chrome.browserAction.onClicked
Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.
To use:
// In your background script
chrome.browserAction.onClicked.addListener( function() {
// Do stuff
});
If, however, you do have a popup, then, as the docs mention, this event will not fire. Then your code is more appropriate: you just need to send a message from the popup and catch it in the background script whenever it is opened. See a full example in this answer.

Related

Chrome extension: Activate and execute background.js on click from popup.js

As I understand from Manage Events with Background Scripts and Migrate to Event Driven Background Scripts background script should be activated when events triggered.
background.js
chrome.runtime.onMessage.addListener((message, sender, reply) => {
const json = message.data;
// some code
reply({ result: true })
return true;
});
popup.js
chrome.runtime.sendMessage({ data: [<ArrayWithData>] },
function (response) {
logger.log(response);
}
);
Everything works well, but only in case of active background.
Why background not become active? Can someone explain what is my mistake?
Or how can I activate and execute background.js on click from popup.js?
I know that if I change persistence: true in manifest.json or just remove it, everything will works fine. But I want to keep persistence false and trigger background.js when needed.
You missed this part in the documentation that explains how a background script should be activated from popup.js. After retrieving the background page object, you just need to call any function or even access a field.
I always put this at the top of my popup.js:
// Initialize background page
chrome.runtime.getBackgroundPage(function(backgroundPage) {
console = backgroundPage.console;
})
That way I can also view console logs from the popup together with logs from the background view

Messaging between content script and popup script in Chrome extension

I'm trying to create a popup chrome extension that shows information about the DOM in the current page, which seems to require messaging. I've been able to send messages to the background, but I need the data to be specific to the current page, as the background is identical to all popups/pages.
In popup.js, I send a message when the DOM is loaded (should trigger when popup is clicked?)
document.addEventListener('DOMContentLoaded', function() {
chrome.runtime.sendMessage({method: "getTableData"}, function response() {
});
});
I also have a listener in the contentscript.js (and background.js for testing)
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(request.method == "getTableData") {
console.log("table request found!");
}
});
Then, when I activate the popup, the background console outputs table request found!, while
the console for the current page doesn't.
Thanks.
You need to use chrome.tabs.sendMessage instead of chrome.runtime.sendMessage to send a message to a content script.

Executing script on a precise tab in Google Chrome extension

I want to execute a script on a precise tab of my browser. This script will give back a value.
I don't know what I have to use. The Doc says that contentScript are called on every loading of a new page. I just want to execute the script once the user clicked on a button in my popup.html.
In your contentScript file add listener like this:
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
//do job
sendResponse(...);
});
And in your popup.html on click event:
chrome.tabs.sendMessage(tabid, "message", function responseCallback(response) {
//...
});
more info http://developer.chrome.com/extensions/tabs.html#method-sendMessage

Message passing: Background script to closing tab

I'm a javascript novice writing my first Chrome extension and I'm stuck on message passing. My extension includes a background script, a browser action icon, and a content script. The content script (a timer that measures the number of second spent in tab) needs to update the background script and change the icon when the tab is closed, but since the content script cannot access the tab onRemove event, it needs to listen for a message from the background script.
Here's how I've set up the background script listener to listen for closed tabs:
// Listen for closed tabs.
chrome.tabs.onRemoved.addListener(function(tab) {
send_closed_message();
});
function send_closed_message () {
chrome.tabs.getSelected(null, function(tab) {
console.log("sending tab_closed to tab " + tab.id);
chrome.tabs.sendRequest(tab.id, {close: true},
function(response) {
console.log(response.timer_stop); });
});
}
And here's the function in the content script that listens for this message.
function main () {
console.log("main()");
timer = new Timer();
timer.start();
// Listen for window focus
window.addEventListener('focus', function() { timer.start(); } );
// Listen for window blur
window.addEventListener('blur', function() { timer.stop(); } );
// Listen for tab close
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url:
"from the extension");
if (request.close === true) {
sendResponse({timer_stop: "stopped"});
timer.stop();
}
});
}
I do not see a response from the content script in the background script console. Since I'm closing the tab, I can't view the content script console. Where is the message going wrong? Is there a better way to debug this? Is there another way the content script could listen for when its tab closes?
I believe the onRemoved on background happens when the tab is already being closed, so probably there is no enough time for the context to receive your message and replay back to the background script.
Maybe is a good idea for the context to keep sending messagens to background every second with its count value. And when the background receives the onRemoved event it simply uses the last received value as the live time of that page.

Load popup.html from chrome.pageAction.onClicked.addListener

I have a page action popup that works when loaded from the manifest file. However I want to get the tab information for the tab that was clicked to launch the popup. I can get the tab information from chrome.pageAction.onClicked.addListener but I don't know how to launch popup.html from inside pageAction.onClicked.
You cannot have both a pageAction.onClicked:
onClicked
This event will not fire if the page action has a popup.
What you can do, though, is fetching the current tab information with the Tabs module when the popup is loaded:
chrome.tabs.getCurrent(function(tab) {
// tab contains information about the current tab
});
I found a workaround for what I wanted to do. On the background page:
chrome.tabs.onActiveChanged.addListener(OnActiveChanged);
function OnActiveChanged( tabId, selectInfo )
{
chrome.tabs.get( tabId, function( tab ){
window.activeTab = tab;
} );
}
This captures the tab each time the tab changes. Then in my popup's function gets the tab from the background page:
function OnLogin( )
{
backgroundWindow = chrome.extension.getBackgroundPage();
var activeTab = backgroundWindow.activeTab;
...
}
Be careful when you debug the code though. The debugger causes a tab change event which changes the tab away from the tab that launched the popup.

Categories