chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.postMessage({joke: "Knock knock"});
});
我想在這個Chrome API函數之外使用'port',我該怎麼做?調用javascript函數結果函數
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.postMessage({joke: "Knock knock"});
});
我想在這個Chrome API函數之外使用'port',我該怎麼做?調用javascript函數結果函數
簡單:
要麼調用一個函數的響應之後,價值傳遞給它:
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
創建一個全局變量和效應初探分配給它
var portValue;
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.postMessage({joke: "Knock knock"});
portValue = port;
});
取決於您想如何使用該值,您可以調整任何方法。
這是否解決您的問題?
var currentPort;
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.postMessage({joke: "Knock knock"});
currentPort = port;
});
Uncaught TypeError:無法讀取未定義的屬性'postMessage' CODE: var currentPort; chrome.runtime.onConnect.addListener(功能(端口){ console.assert(port.name == 「knockknock」); //功能aanroepen(){// port.postMessage({笑話:「敲敲入「}); //} port.postMessage({joke:」Knock knock「}); currentPort = port; }); currentPort.postMessage({joke:「敲敲」}); – user1857116
看起來你正試圖在偵聽器被調用之前在'currentPort'上調用'postMessage'。 –
someFunction function(){
return chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.postMessage({joke: "Knock knock"});
return port;
});
var port = someFunction();
你嘗試端口變量傳遞到另一個方法,而不是立即調用呢? –