【问题标题】:Send text with post method from chrome extension使用 chrome 扩展的 post 方法发送文本
【发布时间】:2014-05-15 15:38:14
【问题描述】:

发送带有 chrome 扩展的大文本

我正在尝试使用我的 chrome 扩展程序将存储在本地存储中的大文本发送到站点。我看过这个answer 并使用此代码

function ls(){return localStorage['txt'];}
function fakePost() {   
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "http://cvsguimaraes.altervista.org/fiddles/postcheck.php");
var params = {action: ls()};
for(var key in params) {
    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", key);
    hiddenField.setAttribute("value", params[key]);
    form.appendChild(hiddenField);
}
document.body.appendChild(form);
form.submit();
};
fakePostCode = fakePost.toString().replace(/(\n|\t)/gm,'');

chrome.browserAction.onClicked.addListener(function (t) {
chrome.tabs.create({"url" : "javascript:"+fakePostCode+"; fakePost();"});
});

但是 ls 没有定义。我怎样才能发送这个文本?而且我没有使用 XmlHTTP,因为我需要 在新标签中打开它

【问题讨论】:

  • 删除了我的答案,因为我误读了您链接到的答案。请在此问题中包含相关代码。

标签: javascript google-chrome post google-chrome-extension


【解决方案1】:

基本上,答案是您不能使用所描述的方法。您的大数据不适合 URL,并且您通过 URL 注入的代码根本无法与扩展代码交互。

您需要一个替代解决方案,但幸运的是它应该很简单。您可以在将发布数据的扩展程序中包含一个 html 文件,然后打开该页面。该 HTML 文件是您扩展程序的一部分,可以访问其 localStorage

编辑:我创建了一个通用解决方案,请参阅this answer

类似的东西:

post.html:

<html>
    <head>
    </head>
    <body>
        <script src="post.js"></script>
    </body>
</html>

post.js:

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "http://cvsguimaraes.altervista.org/fiddles/postcheck.php");
var params = {action: localStorage['txt'];};
for(var key in params) {
    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", key);
    hiddenField.setAttribute("value", params[key]);
    form.appendChild(hiddenField);
}
document.body.appendChild(form);
form.submit();

background.js:

chrome.browserAction.onClicked.addListener(function (t) {
    chrome.tabs.create({"url" : chrome.runtime.getURL("post.html")});
});

【讨论】:

  • 非常感谢!它可以工作,但是您应该在 post.html 中加载脚本,而不是在 head 中,而是在 body 中,因为当脚本在 head 中加载时,它找不到要附加表单的正文
  • 感谢您的关注。到家后,我会把这个方法概括一下,并把它作为原始问题的答案。
  • 我创建了一个通用解决方案并将其发布在at the original question。谢谢,这是一个有趣的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-13
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多