0
chrome.runtime.onConnect.addListener(function(port) {
   console.assert(port.name == "knockknock");
   port.postMessage({joke: "Knock knock"});
});

I want to use 'port' outside this Chrome API function, how do I do that?

Calvin
  • 347
  • 1
  • 4
  • 18

3 Answers3

2

Simply:

either call a function after the response to pass value to it:

chrome.runtime.onConnect.addListener(function(port) {
   console.assert(port.name == "knockknock");
   port.postMessage({joke: "Knock knock"});
   callback(port);

});

function callback(value){
   console.log(value); //accessed value outside that function
}

OR

create a global variable and assign the reponse to it

var portValue;
chrome.runtime.onConnect.addListener(function(port) {
   console.assert(port.name == "knockknock");
   port.postMessage({joke: "Knock knock"});
   portValue = port;

});

Depends on how you want to use the value, you can adapt any of the methods.

Rahul Arora
  • 4,503
  • 1
  • 16
  • 24
0

Does this solve your problem?

var currentPort;
chrome.runtime.onConnect.addListener(function(port) {
   console.assert(port.name == "knockknock");
   port.postMessage({joke: "Knock knock"});
   currentPort = port;
});
Régis B.
  • 10,092
  • 6
  • 54
  • 90
  • Uncaught TypeError: Cannot read property 'postMessage' of undefined CODE: var currentPort; chrome.runtime.onConnect.addListener(function(port) { console.assert(port.name == "knockknock"); //function aanroepen(){ // port.postMessage({joke: "Knock knock"}); //} port.postMessage({joke: "Knock knock"}); currentPort = port; }); currentPort.postMessage({joke: "Knock knock"}); – Calvin Aug 02 '16 at 13:58
  • Looks like you are trying to call `postMessage` on `currentPort` before the listener has been called. – Régis B. Aug 02 '16 at 14:13
0
someFunction function(){
    return chrome.runtime.onConnect.addListener(function(port) {
     console.assert(port.name == "knockknock");
     port.postMessage({joke: "Knock knock"});
     return port;

});

var port = someFunction();