Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
});
like image 591
Ramon Villain Avatar asked Aug 15 '26 18:08

Ramon Villain


1 Answers

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", ...);

like image 135
0xcaff Avatar answered Aug 17 '26 08:08

0xcaff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!