cvsguimaraes 答案中的代码适用于短数据字符串,可以放入 URL。
正如this question 所证明的那样,情况并非总是如此。
Kenny Evitt 的回答暗示了解决方案。我为这个问题做了一个实现,并花时间来概括它。我在这里介绍它。
这个想法是打开一个与扩展程序捆绑在一起的页面 (post.html),通过消息传递给它所需的信息,然后从该页面执行 POST。
post.html
<html>
<head>
<title>Redirecting...</title>
</head>
<body>
<h1>Redirecting...</h1>
<!-- Decorate as you wish, this is a page that redirects to a final one -->
<script src="post.js"></script>
</body>
</html>
post.js
var onMessageHandler = function(message){
// Ensure it is run only once, as we will try to message twice
chrome.runtime.onMessage.removeListener(onMessageHandler);
// code from https://stackoverflow.com/a/7404033/934239
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", message.url);
for(var key in message.data) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", message.data[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form.submit();
}
chrome.runtime.onMessage.addListener(onMessageHandler);
background.js(或扩展内的其他非内容脚本)
function postData(url, data) {
chrome.tabs.create(
{ url: chrome.runtime.getURL("post.html") },
function(tab) {
var handler = function(tabId, changeInfo) {
if(tabId === tab.id && changeInfo.status === "complete"){
chrome.tabs.onUpdated.removeListener(handler);
chrome.tabs.sendMessage(tabId, {url: url, data: data});
}
}
// in case we're faster than page load (usually):
chrome.tabs.onUpdated.addListener(handler);
// just in case we're too late with the listener:
chrome.tabs.sendMessage(tab.id, {url: url, data: data});
}
);
}
// Usage:
postData("http://httpbin.org/post", {"hello": "world", "lorem": "ipsum"});
注意双重消息:使用chrome.tabs.create 回调,我们不能确定监听器是否准备就绪,也不能确定它还没有完成加载(尽管在我的测试中,它总是在加载)。但安全总比后悔好。