open a chrome tab from content script - javascript

I need to open a chrome tab using content script.
I checked message passing in chrome example and tried this
In content script:
chrome.runtime.sendMessage({greeting: "hello"}, function (response) {
console.log(response.farewell);
});
And in background.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
chrome.extension.getBackgroundPage().console.log('resp.type');
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello") {
chrome.tabs.create({url: 'http://google.com'});
sendResponse({farewell: "goodbye"});
}
});
It is working well, the problem is that the tab is opening but also lots of tabs get opened...What I need to do to open just one tab?

When you run the content script it also runs in the new tab that you opened so it ends up opening an infinite amount of tabs. To limit this, you can put the tabs.create inside of a function that doesn't run immediately on page load.

The problem is most likely that you are calling the "chrome.runtime.onMessage.addListener" multiple times, so when it does get a message, all the listeners you added are opening a tab, once for each one that was setup.

Related

OnActivated is only working when new tab opened

I'm trying to communicate with the content script of the tab that has just been switched to using message passing. Here is my code in the background.js script.
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.sendMessage(activeInfo.tabId, { greeting: "hello" }, function(response) {
console.log(response.farewell);
});
});
And here is my code in my content script:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
sendResponse({ farewell: "goodbye" });
loadContent();
});
Is the content script no longer listening in an inactive tab even when it's switched back to that tab? Why does this only run in a newly opened tab?
To further clarify why I want to do this, sometimes tabs are left open without reloading, and my script has already been executed. When information pertaining to the script changes using the popup options, I want the content to reload on tab change, and a particular function to run again without reloading the page. Therefore, injecting the content script is less than ideal since it's already been executed.
Try this :
background.js
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
chrome.tabs.sendMessage(activeInfo.tabId,
{ greeting: "hello" }, function(response) {
console.log(response.farewell);
});
});
});

Google Chrome Extension: Cannot launch Print dialog

I'd like to launch the print dialog on button click in my google chrome extension. The code seems to be working when the extension's html file is opened as a standalone file, but not when it's loaded as an extension.
HTML:
<input id="print_page" type="button" value="Print" onclick="print_p()" />
JavaScript: function print_p(){ window.print();}
Any idea as to what's wrong?
Aside from the inline JavaScript problem that I mentioned as a duplicate, it seems that invoking the print dialog from a popup (or a background page) is impossible.
A workaround would be to have a "print helper" page in your extension, that opens in a normal tab and can open a print dialog.
A possible architecture:
On a click in a popup, data to print is being sent to the background page:
function printClick(){
chrome.runtime.sendMessage({ print: true, data: whateverYouWantToPrint });
}
It's routed through the background page so that you don't have to worry about popup closing.
In the background page, a helper page is opened:
var printData;
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){
if(request.print) {
printData = request.data;
chrome.tabs.create(
{ url: chrome.runtime.getURL("print.html") }
);
}
// ...
});
In the print helper page, a script print.js requests the data, formats it as required and invokes the print dialog:
chrome.runtime.sendMessage({ getPrintData: true }, function(response){
formatDataIntoPage(response.data);
window.print();
});
Back in the background page, serve the data on request from print helper:
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){
// ...
if(request.getPrintData) {
sendResponse({ data: printData });
}
});

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.

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.

Message Passing from Content Scripts to Background Page in Chrome Extensions

Google Chrome Extensions Message Passing Problem :
In this Chrome Extension
My Popup Page:
chrome.browserAction.onClicked.addListener(getMessage);
getMessage();
function getMessage()
{
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});//getting response from content script
});
}
My Script Page :
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
else
sendResponse({});
});
I am not getting any response from the content script.
Edits:
As per #serg , i have moved the code to the background page. But still, it is not working
You can't have chrome.browserAction.onClicked listener if you have popup page attached to the browser action button, it won't fire.
Remove popup, leave only button
Move everything into background page.
Replace tab.id with null.
Remove createFile(); call at the beginning as it won't do anything in this case (content script isn't ready to listen yet).
Don't use alerts for debugging extension, use console.log().

Categories