如何将Chrome扩展程序中保存的Javascript变量传递给Google App Engine应用程序?

时间:2011-10-09 15:02:56

标签: javascript google-app-engine google-chrome-extension

我正在开发一个简单的书签应用程序来学习Google App Engine。此时,我将网址复制并粘贴到http://ting-1.appspot.com/submit,其中包含一个包含网址字段的表单。由于这很麻烦,我想添加镀铬扩展。我刚刚更改了hello world example,现在我使用此代码(as explained here)获取标签的网址:

  <script>
    window.addEventListener("load", windowLoaded, false);
    function windowLoaded() {
      chrome.tabs.getSelected(null, function(tab) {
        document.getElementById('currentLink').innerHTML = tab.url;
        tabUrl = tab.url;
      });
    }
document.write(tabUrl)
  </script>

如何将tabUrl传递给http://ting-1.appspot.com/submit

谢谢!

更新

background.html我改编自Mohamed Mansour's answer

<script>
    //React when a browser action's icon is clicked.
    chrome.browserAction.onClicked.addListener(function(tab) {
        //this gets the url and the title
        chrome.tabs.getSelected(null, function(tab) {
            tabUrl = tab.url
            tabTitle = tab.title

        //this posts the data to the bookmarking app 
        var formData = new FormData();
        formData.append("url", tabUrl);
        formData.append("title", tabTitle);
        formData.append("pitch", "this is a note");
        formData.append("user_tag_list", "tag1, tag2");
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://ting-1.appspot.com/submithandlertest");
        xhr.send(formData);
        });
    });
</script>

1 个答案:

答案 0 :(得分:4)

您使用普通的XHR(XMLHttpRequest)请求。我会把它放在你的background page中。按照此处的示例https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest。我相信你也想提交数据,所以不要忘记。我想你也想要一个POST请求。从MDC上的示例中,您可以通过以下方式联系它:

var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submit");
xhr.send(formData);

确保您拥有manifest中的网址,以获取执行该请求的权限。

"permissions": [
  "tabs",
  " http://ting-1.appspot.com/submit"
],