【问题标题】:How to pass a saved Javascript variable in a Chrome extension to a Google App Engine App?如何将 Chrome 扩展中保存的 Javascript 变量传递给 Google App Engine 应用程序?
【发布时间】:2011-12-04 00:00:17
【问题描述】:

我正在开发一个简单的书签应用程序来学习 Google App Engine。此时,我将 url 复制并粘贴到 http://ting-1.appspot.com/submit 中,它有一个带有 url 字段的表单。由于这很麻烦,我想添加一个 chrome 扩展。我刚刚更改了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>

【问题讨论】:

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


    【解决方案1】:

    您使用普通的 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 中有 URL 以获取执行该请求的权限。

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

    【讨论】:

    • @Mohamed Mansour:感谢您的回答。这非常有效。额外感谢XMLHttpRequest 教程的链接。现在我想添加一个回调函数来表示提交成功。我正在阅读异步请求部分developer.mozilla.org/En/XMLHttpRequest/…,但是如果您对如何在我的情况下添加回调函数有任何实用的建议,那也会很有帮助,或者如果有必要,我稍后会发布另一个问题。我用我使用的代码更新了这个问题。再次感谢。
    猜你喜欢
    • 2013-11-02
    • 2018-12-05
    • 1970-01-01
    • 2014-10-29
    • 2016-03-20
    • 2012-04-16
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多