我正在构建我的第一个chrome扩展程序,它通过从网页抓取网址来创建链接的播放列表。但是,我对我的消息功能感到困惑。我在我的播放列表对象中编写了一个名为'test'的测试函数,我只是尝试将内容脚本发送回的消息(通过getPageInfo函数)分配给我的对象函数中的变量。但是,虽然我收到一条消息,但字符串在return语句和测试函数之间丢失了。这是我的背景脚本:
//BACKGROUND.JS
var Playlist = {
index: 0,
playlist: [],
test: function(info) {
var message = "Get Song";
var song = getPageInfo(message);
alert(song); //Shows undefined
}
};
function getPageInfo(message) {
var s;
chrome.tabs.query({active:true, currentWindow:true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: message}, function(response){
console.log(response.farewell);
s = response.farewell;
alert(s); //Shows "We did it"
});
});
alert(s) //Shows "We did it"
return s;
}
chrome.contextMenus.create({
title: "Add to Playlist",
contexts: ["image", "link", "selection"],
onclick: Playlist.test
});
这是我的内容脚本:
//CONTENT.JS
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if(request.greeting == "Get Song")
sendResponse({farewell: "We did it"}); //My message
});
这是我的清单:
{
"manifest_version": 2,
"name": "RedditDJ",
"description": "This app hides jobs which the user has already clicked on.",
"version": "1.0",
"content_scripts": [
{
"matches": ["http://www.reddit.com/*","https://www.reddit.com/*"],
"js": ["script/jquery-2.1.4.js", "script/content.js"]
}
],
"permissions": [
"http://www.reddit.com/",
"https://www.reddit.com/",
"http://www.youtube.com/",
"https://www.youtube.com/",
"http://www.soundcloud.com/",
"https://www.soundcloud.com/",
"http://*/",
"https://*/",
"tabs",
"contextMenus",
"storage"
],
"browser_action": {
"default_icon": {
"19":"style/img/icon_19.png",
"38":"style/img/icon_38.png",
"128":"style/img/icon_128.png"
},
"default_title": "Reddit DJ",
"default_popup": "popup.html"
},
"background": {
"scripts": ["script/background.js"],
"persistent": true
}
}
我已经把它翻了几天,但我无法弄清楚我做错了什么。有任何想法吗?谢谢!
答案 0 :(得分:0)
您无法将异步功能转换为同步功能。您必须为callback
添加getPageInfo
参数,并将其用于返回值。
这样的事情:
function getPageInfo(message, callback) {
chrome.tabs.query({active:true, currentWindow:true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: message}, function(response) {
console.log(response.farewell);
s = response.farewell;
callback(s);
});
});
}
甚至更好的是使用承诺:
function getPageInfo(message) {
return new Promise(function(resolve, reject) {
chrome.tabs.query({active:true, currentWindow:true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: message}, function(response) {
console.log(response.farewell);
s = response.farewell;
resolve(s);
});
});
});
}
getPageInfo().then(function(value) {
alert(value);
})