Chrome extension create tab and send msg to it - javascript

I tried different things, but it doesn't work.
In my popup.html i've created a button. When i click it, i wan't to create a new tab and send to it a message. Here is the code:
$("#openLink").click(function () {
chrome.tabs.create({url: 'http://jquery.com'}, function (tab) {
console.log(tab.id);
alert(tab.id);
chrome.tabs.sendMessage(tab.id, 'hello');
});
});
And in the content script i try to use this:
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
alert('message received');
});
But it doesn't alert me nothing.
Please help.

Related

Difficulty passing messages between background and content script in chrome extension

I'm attemtping to send a message from the content script to the background script, and send a response in return.
This is what I've got in my background script:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("Message received");
if(request.activeStatusRequest == "disable"){
sendResponse({activeStatusUpdate: "disable"});
}else if(request.activeStatusRequest == "enable"){
sendResponse({activeStatusUpdate: "enable"});
}
return true;
});
This is what I've got in my content script:
printReviews.onclick = function(element) {
if(printReviews.classList.contains("activeButton")){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.executeScript(
tabs[0].id,
{code: `${injectionLiteralGETURL}`}
);
});
toggleClasses(printReviews, "activeButton", "inactiveButton");
chrome.runtime.sendMessage({activeStatusRequest: "disable"}, function(response){
console.log("response received");
console.log(response.activeStatusUpdate);
});
}
else {
toggleClasses(printReviews, "inactiveButton", "activeButton");
chrome.runtime.sendMessage({activeStatusRequest: "enable"}, function(response){
console.log("response received");
console.log(response.activeStatusUpdate);
});
}
};
The rest of the above code works as expected, except that the none of the console logs in the content script run. The console log in the background script does run, however.
Anyone got any ideas as to what I've done wrong?
If you want to try another method, you could try to add a listener in the content script
Content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("Message received from background", response.type, response.activeStatusUpdate);
switch(request.type){
case 'SomeFirstAction'
break;
case 'SomeSecondAction'
break;
}
});
Background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("Message received");
if(request.activeStatusRequest == "disable"){
sendMessageToCurrentTab({type: 'SomeFirstAction', activeStatusUpdate: "disable"});
}else if(request.activeStatusRequest == "enable"){
sendMessageToCurrentTab({type: 'SomeSecondAction', activeStatusUpdate: "enable"});
}
// return true; -> not needed with that method
});
function sendMessageToCurrentTab(message){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, message);
}
}
To have played with callbacks between popup/background/content-script, I prefer just play with messages,because when using sendResponse, the manner it works, it open a port to communicate, but if something change (tab close, popup close), you will have an error because the port will be closed too.
Using the 'Full send message manner', the background need to clearly target the receiver tab.
I also recommand you to use a type or some unique action attribute, because all listener will listen to all action. It will identify the action and it's purpose.
Here I just used a switch in the content script, but the background could use the same logic.
Maybe it's not the greatest way of doing things, but it works well for me.
Hope this can help you

Stop event listener

I made a button which openning new page in new tab for example https://google.com. And I'm sending a message to the background script to start taking the URL of new opened page. The problem is that I don't know how to stop the listener after retrieving the URL. So it's continue the execution even after I closed that tab.
Popup.js
$('#click').click(function(e)
{
chrome.tabs.create({url: 'https://google.com'});
chrome.runtime.sendMessage({greeting: "googleisopened"}, function(response) {
console.log(ok);
});
});
Background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "googleisopened")
{
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
alert(changeInfo.url);
});
}
});
I think you're insterested in this function http://api.jquery.com/off/
It removes all of the events from the object so in your case you could just plug it anywhere in your click event like this:
$(this).off('click');
// Or like this if you want to be specific
$('#click').off('click');
Thanks to everyone who tried to help me. I found a solution by myself.
Instead of using listener I started to use tabs.getSelected to retrieve page URL only when needed (not in cycle as in onUpdated.addListener).
So the background script will be next:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting === "googleisopened")
{
chrome.tabs.getSelected(null, function(tab)
{
chrome.tabs.onUpdated.addListener(mylistener);
function mylistener (tabId, changeInfo, tab)
{
alert(changeInfo.url);
chrome.tabs.onUpdated.removeListener(mylistener);
}
});
}
});

Chrome Extension, send data between tabs

I'm developing a simple extension, but I cannot figure out how to move on. I guess it's a 'simple' question.
The scenario:
The user select an text
Opens the contextual menu and hit the extension
A new tab will open
Fill a textarea w/ the selected/highlighted text
I did the first three items, and to the fourth I tried chrome.tabs.query/executeScript/messaging, ajax post… without success.
function sendReport() {
return function(info, tab) {
var selectedText = info.selectionText;
var cr_url = 'http://localhost/cr/index.php';
var tab = chrome.tabs.create({ url: cr_url }, function(tab){
});
}
}
var OgameToConverter = chrome.contextMenus.create({
"title": "Enviar Relatório",
"contexts": ["selection"],
"onclick": sendReport()
});
You can send messages between tabs by using chrome.runtime.sendMessage or chrome.tabs.sendMessage. To receiving the message, add an listener for the message on the receiving tab by using the chrome.runtime.onMessage.addListener method.
Example:
chrome.tabs.create({ url: cr_url }, function(tab){
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(){});
});
In the tab:
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
// do what you want to the message
});
Or, you can create the window with window.open, send the message with window.postMessage and recieve the message by catching the Message event with something like window.addEventListener("message", ...);

Chrome extension: How to sendMessage form background to background?

My background listener is
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse)
In chrome.contextMenus.onClicked listener, I want to use the message system,I call
chrome.runtime.sendMessage
in the listener, but it's not works.
So, how can I sendMessage from background to background ?
Messages dispatched by a page are not received by the same page.
If you want to be able to re-use the onMessage listener, put it in a separate function. For example:
function alwaysDoSomething() {
console.log('Done something!');
}
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
alwaysDoSomething();
});
chrome.contextMenus.onClicked.addListener(function(info, tab) {
alwaysDoSomething();
});
There is an undocumented method that can be used to manually trigger the events. It is undocumented, so use it at your own risk!
chrome.contextMenus.onClicked.addListener(function(info, tab) {
var message = 'whatever';
var sender = {tab: null, id: chrome.runtime.id};
var sendResponse = function() {};
chrome.runtime.onMessage.dispatch(message, sender, sendResponse);
});
I think you should use chrome.extension.onRequestExternal or chrome.extension.onConnectExternal

Chrome Extension Message Passing - Code included

I have a contentscript called file.js that creates variable "found". I want to send the values of varibale "found" to a textbox in popup.html
In file.js (I know varible found is working, tested using an alert).
chrome.extension.sendRequest({foundlinks: found}, function(response) {
console.log(response);
});
In Popup.html:
function pulllinks(){
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
document.getElementById("box").value = request.foundlinks;
sendResponse({});
});
And on the form in popup.html:
<input type = "button" onclick="pulllinks();" name = "box" id="box" value = "Grab Links From Page" />
However, its not doing anything. Any ideas?
Thanks!
You need to be sending requests in the opposite direction - from popup to content script:
popup.html:
function pulllinks(){
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {cmd: "findLinks"}, function(response) {
document.getElementById("box").value = response.foundlinks;
});
});
}
file.js:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.cmd == "findLinks") {
//calculate "found" value and send it back
sendResponse({foundlinks: found});
}
});
First of all, your listener for onRequest should exist from the start, so move it outside of the pulllinks function. Secondly, how are you making sure that your sendRequest is being fired while the popup is open?

Categories