我试图传递标签对象tabout
,以便找到网页的说明和标题。
当我用一些断点调试代码时,它返回了值,但是当我运行它时,它没有返回描述。
代码有问题吗?
function computeDescription(tabout)
{
var code = 'var meta = document.querySelector("meta[name=\'description\']");' +
'if (meta) meta = meta.getAttribute("content");' +
'({' +
' title: document.title,' +
' description: meta || ""' +
'});';
var desc;
var message = document.querySelector('#message');
chrome.tabs.executeScript(tabout.id,{code: code}, function(results) {
if (chrome.extension.lastError) {
message.innerText = 'There was an error injecting script :\n'+chrome.extension.lastError.message;
}
if (!results) {
return;
}
var result = results[0];
// Now, do something with result.title and result.description
console.log(result.title);
console.log(result.description);
desc=result.description;
});
return desc;
}
答案 0 :(得分:0)
看起来你假设你给executeScript
的回调将在computeDescription
返回之前执行。这不是真的; executeScript
异步执行,并且在computeDescription
返回之前,您的回调将从不运行。
为了解决这个问题,您需要采用异步模型来定义computeDescription
。不是返回值,而是采用回调参数并在数据就绪时调用它。
function computeDescription(tabout, callback) {
var code = 'var meta = document.querySelector("meta[name=\'description\']");' +
'if (meta) meta = meta.getAttribute("content");' +
'({' +
' title: document.title,' +
' description: meta || ""' +
'});';
var message = document.querySelector('#message');
chrome.tabs.executeScript(tabout.id, {code: code}, function(results) {
if (chrome.extension.lastError) {
message.innerText = 'There was an error injecting script :\n'+chrome.extension.lastError.message;
}
if (!results) {
callback();
}
callback(results[0].description);
});
}
然后你的用法同样从
转换console.log('Le description is: ' + computeDescription(tab));
到
computeDescription(tab, function(description) {
console.log('Le description is: ' + description);
});