Using JQuery's post function in chrome extension

柔情痞子 提交于 2019-12-25 01:06:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!