我正在开发一个简单的书签应用程序来学习 Google App Engine。此时,我将 url 复制并粘贴到 http://ting-1.appspot.com/submit 中,其中有一个包含 url 字段的表单。由于这很麻烦,我想到添加一个 chrome 扩展。我刚刚更改了 hello world example,这样现在我就可以使用此代码 (as explained here) 获取选项卡的 URL:
<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>
最佳答案
您使用普通的 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"
],
关于javascript - 如何将 Chrome 扩展程序中保存的 Javascript 变量传递到 Google App Engine 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7704394/