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?
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?
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.
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;
});
someFunction function(){
return chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.postMessage({joke: "Knock knock"});
return port;
});
var port = someFunction();