此问题与所引用的问题(将我的帖子标记为重复)不同,这是因为从chrome扩展名调用本地服务器。我知道如何使本地烧瓶服务器在正常情况下工作。
http://localhost/*
已添加到清单文件。
更新:我将ajax代码从内容脚本移到了一个新的js文件,我将其称为requestScript.js:
$.ajax({
type: "GET",
url: "http://localhost:5000/getsourceinfo",
dataType: "json",
data: {
"photo_id": photo_id
},
contentType: "application/json; charset=utf-8",
success: function(result){
//send message back to background script
chrome.runtime.sendMessage(tabs[0].id, {message:"readsource", value: result})
},
error: function(request, status, error) {
console.log("Error");
}
})
在contentScript.js中,单击按钮:
chrome.runtime.sendMessage({message: "getsource", value: "1"}, function(response) {
//do something here if required
console.log("Sent message to background")
})
在background.js中,收听来自contentScript.js的消息,
if (request.message == 'getsource') {
chrome.tabs.executeScript(null, {
code: 'var photo_id = ' + request.value
}, function() {
chrome.tabs.executeScript(null, {file: "requestScript.js"})
})
}
另外,在background.js中,侦听来自requestScript.js的消息,
if (request.message == 'readsource') {
//send message back to content script
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {message: 'readphotosource', value: request.value}, function(response) {});
});
}
最后,从contentScript.js中的background.js中读取消息集:
if (request.message == 'readphotosource') {
//handle the response here
}
我仍然收到错误的请求错误。