当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Returning value from get function with content script

问题描述:

I'm trying to make a function to return data from a worker but it doesn't seem to work, how should I do this?

function getExample()

{

worker = tabs.activeTab.attach({contentScript:

"var testText = document.getElementsByClassName('exampleElement')[0].children[1].innerHTML;" +

"self.port.emit('test', testText);"

});

worker.port.on('test', function(test) {return testText;});

}

网友答案:

The port.on API is pretty much the same concept as a DOM event listener. You cannot simply return something from the listener function and expect it to propagate to outer function. It isn't even guaranteed your listener function will be called synchronously. Your current function is equivalent to:

function getExample() {
    worker.port.on('test', function(testText) {return testText;});
    return undefined;
}

You need to provide a callback function and have your code assume that things are asynchronous:

function getExample(callback) {
    /* ... */
    worker.port.on('test', function(testText) { callback(testText); });
    // or shorter:
    worker.port.on('test', callback);
}

PS: I just noticed that your on function has a parameter named test, but the function body uses the undefined testText. This is an issue, too, but an unrelated one and likely only introduced when you simplified your real code to fit into a question here.

分享给朋友:
您可能感兴趣的文章:
随机阅读: