问题
I'm trying to post to localhost server from within a chrome extension and it doesn't seem to work.
Here are my files:
manifest:
{
"name": "Send to server",
"version": "1.1",
"background": { "page": "background.html"},
"permissions": ["experimental", "tabs", "<all_urls>"],
"browser_action": {"name": "Send to server", "default_icon": "icon.png", "default_popup":"popup.html" },
"icons": { "16": "16.png" },
"manifest_version": 2
}
The background.html is very brief, it just points to "http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" and to "background.js". (I use it just to be able to include JQuery and use it at background.js. Is there another way for it?)
background.js:
chrome.tabs.onUpdated.addListener(SendToServer);
function SendToServer(tabId, changeInfo, tab) {
chrome.tabs.getSelected(null, function(tab) {
if (changeInfo.status === 'complete'){
chrome.experimental.infobars.show({
tabId: tab.id,
path: "infobar.html"
});
var strVar = "A page was loaded";
alert("Before sending: " + strVar);
$.post("http://localhost/MyDomain", {var: strVar},
function(strVar ) { alert("Sending..."); }
);
}
})
};
Now, alert("Before sending: " + strVar); is performed, so till here I'm doing well. But the .post isn't done.
Any idea?
Thanks,
回答1:
If you debug your background page you will find out that there is a security error. You are trying to load javascript from remote source (ajax.googleapis.com) while you haven't explicitly allowed that in the manifest file. And without jQuery, $.post
can't run. You need to relax default Content Security Policy (be sure to load jQuery over https).
If fact, what you should actually do in this particular case, is to include jQuery file in your extension and load it accordingly in backtround.html
. Extension is not a website, remote call takes a lot of time compared to simple HDD fetch. In addition, using remote javascript files makes extension unusable/unstable when there is no internet connection.
来源:https://stackoverflow.com/questions/13186940/using-jquerys-post-function-in-chrome-extension