Cross-domain post with Greasemonkey?

旧巷老猫 提交于 2019-12-23 05:51:43

问题


I need to post in the background with Greasemonkey. I tried to create an iframe dynamically and post to it, but it didn't work:

function crossDomainPost() {
    // Add the iframe with a unique name
    var iframe = document.createElement("iframe");
    var uniqueString = "CHANGE_THIS_TO_SOME_UNIQUE_STRING";
    document.body.appendChild(iframe);
    iframe.style.display = "none";
    iframe.contentWindow.name = uniqueString;

    // construct a form with hidden inputs, targeting the iframe
    var form = document.createElement("form");
    form.target = uniqueString;
    form.action = "http://INSERT_YOUR_URL_HERE";
    form.method = "POST";

    // repeat for each parameter
    var input = document.createElement("input");
    input.type = "hidden";
    input.name = "INSERT_YOUR_PARAMETER_NAME_HERE";
    input.value = "INSERT_YOUR_PARAMETER_VALUE_HERE";
    form.appendChild(input);

    document.body.appendChild(form);
    form.submit();
}


Some people say even if we post, we won't be able take the values. if we can't, just making the user visit the page is enough. it can be in JS, jQuery, AJAX post. Not only the form-iframe trick.


回答1:


Greasemonkey has built-in support for cross-domain posting. You do not need to use jsonp, nor an iframe. Use the GM_xmlhttpRequest function.

Rather than trying to build a form and post it, you send form-encoded data directly:

var formData1   = "1 INSERT_YOUR_PARAMETER_VALUE_HERE";
var formData2   = "2 INSERT_YOUR_PARAMETER_VALUE_HERE";
var formData3   = "3 INSERT_YOUR_PARAMETER_VALUE_HERE";
// etc.

GM_xmlhttpRequest ( {
    method:     "POST",
    url:        "http://YOUR_SERVER.COM/YOUR_PATH",
    data:       "formData1=" + encodeURIComponent (formData1)
                + "&" + "formData2=" + encodeURIComponent (formData2)
                + "&" + "formData3=" + encodeURIComponent (formData3)
                // etc.
                ,
    headers:    {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    onload:     function (response) {
        console.log (response.responseText);
    }
} );


来源:https://stackoverflow.com/questions/11275378/cross-domain-post-with-greasemonkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!