I`m making chrome extension and have problem with submitting from background.html
For example this works:
var url="some url";
chrome.tabs.create({"url":url, selected:true});
but if i`ll try to do:
document.forms["test"].submit();
It works only once when I just installed extension or after reboot
UPDATE
I am trying to submit this form which is in background.html:
<FORM action="some url" name="test" id = "test" method="post" target="_blank" >
<input type="hidden" id="test" name="test" value="12" />
<input type="hidden" id="addr" name="addr" value="" />
</form>
then i create menu
chrome.contextMenus.create({"title": "test", "parentId": parentID, "contexts":["selection"], "onclick": SubmitFunction})开发者_开发百科;
SubmitFunction(){
document.forms["test"].submit();
}
It works only one time after rebooting or after installation
background.html exists in the extension context and can not directly alter pages b/c pages exist within their own page context. In your case background.html has no context for any particular page/tab when you call submit(). So you will probably need to use a content script and then communicate with it via message passing.
If you want to send a POST request to a web server you should use XMLHttpRequest
. If you know jQuery or any other framework, they usually provide convenient wrappers for this:
$.post("some_url", { test: "...", addr: "..." }); //jQuery
If not, then you can use XMLHttpRequest
directly:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
console.log("done");
}
}
xhr.open("POST","some_url",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("test=TEST_VALUE&addr=ADDRESS_VALUE");
More details here.
I was having the same issue while developing my chrome extension. My background page had a form with a _blank target. It would only open the new window once, but if I tried to submit it again it quietly did nothing. I don't know why this happens, but here is my solution.
function randomString(){
return ((Math.PI * Math.max(0.01, Math.random())).toString(36).substr(2, 5));
}
function submitMyForm(){
... //do whatever form preparations here
var rn = randomString();
$('#myForm')[0].target = rn;
window.open('', rn);
$('#myForm').submit();
}
Basically I changed the target to a random name and it just worked after that. Why? I don't know, maybe someone else can clairify that, but his works for me.
(I'm also using JQuery,but if you need vanilla JavaScript just replace with "document.getElementById('myForm')" where needed)
精彩评论