本文介绍了打开标签并在Firefox WebExtension中对其发出POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用低级SDK API迁移我的firefox 插件 WebExtension,有时我想将经过网址编码的数据发布到新标签页中.
I try to migrate my firefox addon wich use low level SDK API to WebExtension and at some point I want to POST data url-encoded to a new tab.
使用低级API,可以通过以下代码进行操作:
With the low level API it is possible through the following code:
const querystring = require('sdk/querystring');
let stringStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
stringStream.data = querystring.stringify(params); // params is a json data
let postData = Cc["@mozilla.org/network/mime-input-stream;1"].createInstance(Ci.nsIMIMEInputStream);
postData.addHeader("Content-Type", "application/x-www-form-urlencoded");
postData.addContentLength = true;
postData.setData(stringStream);
var tabBrowser = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator).getMostRecentWindow("navigator:browser").gBrowser;
var selectedTabIndex = tabBrowser.tabContainer.selectedIndex;
var newTab = tabBrowser.loadOneTab("https://myurl.com/", {
inBackground: false,
postData: postData
});
tabBrowser.moveTabTo(newTab, selectedTabIndex + 1);
但是我还没有找到等效的WebExtension.
But I haven't found a WebExtension equivalent.
是否可能或唯一的解决方案是创建表单并用js提交?
Is it possible or the only solution is to create a form and submit it in js?
推荐答案
现在唯一的解决方案是在新选项卡中创建一个表单并提交.在后台脚本中:
Right now the only solution is to create a form in the new tab and submit it.In the background script:
// tab creation
browser.tabs.create({ index: tab.index + 1, url: "https://myurl.com/" }, function (tab) {
// load content script submitForm.js
browser.tabs.executeScript(tab.id, { file: "submitForm.js" }, function () {
// send message to submitForl.js with parameters
chrome.tabs.sendMessage(tab.id, {url: tab.url, message: 'hello world'});
});
});
submitForm内容:
submitForm content:
function submitForm(request, sender, sendResponse)
{
var f = document.createElement('form');
f.setAttribute('method','post');
f.setAttribute('action','https://myurl.com/form');
var f1 = document.createElement('input');
f1.setAttribute('type','hidden');
f1.setAttribute('name','url]');
f1.setAttribute('value', request.url);
f.appendChild(f1);
var f2 = document.createElement('input');
f2.setAttribute('type','hidden');
f2.setAttribute('name','content');
f2.setAttribute('value', request.message);
f.appendChild(f2);
document.getElementsByTagName('body')[0].appendChild(f);
f.submit();
}
// listen for messages and execute submitForm
chrome.runtime.onMessage.addListener(submitForm);
这篇关于打开标签并在Firefox WebExtension中对其发出POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!