Javascript form.submit() doesn't work in Safari - javascript

I have a simple function that create, append and submit a form from an HTML page, it works in all browser except Safari. I can't figure out why, any hint will be very welcome
here's my function:
function open(method, url, data, target) {
var form = document.createElement("form");
form.action = url;
form.method = method;
form.target = target;
if (data) {
for (var i = 0; i < data.length; i++) {
let input = document.createElement("textarea");
input.name = i.toString();
input.innerText = data[i];
form.appendChild(input);
}
}
form.style.display = "none";
document.body.appendChild(form);
form.submit();
form.remove();
}
// use example
var data = ["text1", "text2", "text3", "text4", "text5", "text6"];
open("POST", "../result.php" , data, "_blank");
Ps: if it's possible I would avoid using JQuery

You have set target="_blank" and are triggering the function during the script load (i.e. not from a user event like a click).
Since you are trying to open an automatic popup when the page loads, Safari is blocking you.
Don't use _blank or wait until something is clicked before calling your function.

Related

Disable "Changes you made may not be saved" pop-up window

I use the following frontend code to export a .csv document.
HTML
<form id="tool-export" method="post" action="export/">{% csrf_token %}
<a id="export-link" class="btn btn-sm btn-primary" href="#">DOWNLOAD</a>
</form>
JS
$('#export-link').click(function(e) {
e.preventDefault();
var link = $(this);
var form = link.closest('form');
var project_id = proj_id.find(":selected").val();
var input = $('<input>').attr('type', 'hidden').attr('name', 'project_id').val(project_id);
form.append($(input));
var project_type = proj_type.val();
input = $('<input>').attr('type', 'hidden').attr('name', 'project_type').val(project_type);
form.append($(input));
form.submit();
});
Export works well and I get the correct document. But also I receive the Changes you made may not be saved message after clicking on the export link. How to disable this message? I don't want to see it.
#Dekel helped me to get it.
The message is the beforeunload event.
And I can disable it with window.onbeforeunload = null;.
JS
$('#export-link').click(function(e) {
window.onbeforeunload = null;
e.preventDefault();
var link = $(this);
var form = link.closest('form');
var project_id = proj_id.find(":selected").val();
var input = $('<input>').attr('type', 'hidden').attr('name', 'project_id').val(project_id);
form.append($(input));
var project_type = proj_type.val();
input = $('<input>').attr('type', 'hidden').attr('name', 'project_type').val(project_type);
form.append($(input));
form.submit();
});
In jQuery simply use :
$(window).off('beforeunload');
I had the same problem.
window.onbeforeunload = function () {
// Your Code here
return null; // return null to avoid pop up
}
I've had the same error with embedding Google-Form in Chrome,
I can verify that none of the found solutions helped me. Here is the screenshot of my pop-up:
The only solution I've managed to implement was hiding the element and then unhiding/creating the new iframe with the current embed. Here's the part of my code:
if (oldvalue !== value) { // checks the id of the form (value) is not the same
// set value of the id
$('#info').text(value);
// check the element exists
let exists = value;
if($("#" + value).length == 0) {
//it doesn't exist
exists = false;
}
// hide all child elements of the div for forms
parent.children().hide();
// create new node if needed
if (!exists)
{
// create new form element and embed the form
$("#google-form").clone().attr("id",value).attr('src', record.url).appendTo(parent);
}
// unhide error element
$("#" + value).show();
}
The full code of my solution is here.

Form Submit onbeforeunload in Firefox

I am writing a javascript function that creates an iframe and a form that targets the frame. The form should submit the form on before unloading the page. The code works with every browser, except Firefox.
function unloadPage(message) {
actionUrl = "https://test.testpage.com/log/logwatch.lw"
var iframe = $('<iframe id="pageLogFrame" name="pageLogFrame" style="display:none;"></iframe>');
var form = $('<form id="pageLogForm" target="pageLogFrame" method="post"></form>');
$('body').append(iframe);
$('body').append(form);
form.attr('action',actionUrl);
var input = $('<input type="hidden" name="pageLog" />');
form.append(input);
input.val(message);
form.submit();
};
window.onbeforeunload = function(){
var message = "sampleMessage";
unloadPage(message);
};
Does anyone have a solution or an idea how to make this work in Firerox? Thanks!
Firefox requires you to specify a void return value.
The function should assign a string value to the returnValue property of the Event object and return the same string.
taken from: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};

remove javascript form.setAttribute action

I am trying to disable the form action in this script. Can someone please help me disable ore remove the form "action" variable? I am using the scripting a form to upload an image but when I submit the form the action that is set on this script is called.
Can someone please advice?
function $m(theVar){
return document.getElementById(theVar)
}
function remove(theVar){
var theParent = theVar.parentNode;
theParent.removeChild(theVar);
}
function addEvent(obj, evType, fn){
if(obj.addEventListener)
obj.addEventListener(evType, fn, true)
if(obj.attachEvent)
obj.attachEvent("on"+evType, fn)
}
function removeEvent(obj, type, fn){
if(obj.detachEvent){
obj.detachEvent('on'+type, fn);
}else{
obj.removeEventListener(type, fn, false);
}
}
// browser detection
function isWebKit(){
return RegExp(" AppleWebKit/").test(navigator.userAgent);
}
// send data
function ajaxUpload(form){
var detectWebKit = isWebKit();
var get_url = 'upload.php';// php file
var div_id = 'upload_area';// div id where to show uploaded image
var show_loading = '<img src="img/loading.gif" />';// loading image
var html_error = '<img src="img/error.png" />';// error image
// create iframe
var sendForm = document.createElement("iframe");
sendForm.setAttribute("id","uploadform-temp");
sendForm.setAttribute("name","uploadform-temp");
sendForm.setAttribute("width","0");
sendForm.setAttribute("height","0");
sendForm.setAttribute("border","0");
sendForm.setAttribute("style","width: 0; height: 0; border: none;");
// add to document
form.parentNode.appendChild(sendForm);
window.frames['uploadform-temp'].name="uploadform-temp";
// add event
var doUpload = function(){
removeEvent($m('uploadform-temp'),"load", doUpload);
var cross = "javascript: ";
cross += "window.parent.$m('"+div_id+"').innerHTML = document.body.innerHTML; void(0);";
$m(div_id).innerHTML = html_error;
$m('uploadform-temp').src = cross;
if(detectWebKit){
remove($m('uploadform-temp'));
}else{
setTimeout(function(){ remove($m('uploadform-temp'))}, 250);
}
}
addEvent($m('uploadform-temp'),"load", doUpload);
// form proprietes
form.setAttribute("target","uploadform-temp");
form.setAttribute("method","post");
form.setAttribute("action",get_url);
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
// loading
if(show_loading.length > 0){
$m(div_id).innerHTML = show_loading;
}
// submit
form.submit();
return true;
}
Hook your function in the onsubmit of the form and return false; at the end - that will cancel the standard form submit.
form.submit(evt);
evt.preventDefault();
}
Will also bypass the actual form submission process, per the jQuery .submit() documentation:
Now when the form is submitted, the message is alerted. This happens
prior to the actual submission, so we can cancel the submit action by
calling .preventDefault() on the event object or by returning false
from our handler.

Javascript Function Removal and Replacement

My site is AJAX based so I have an window.onbeforeunload = function(){};. However, I have mailto link and when I click those mailto links, the confirm reload pops up, which I don't like. Is there a way to write a function to remove the window.onbeforeunload = function(){};, pull up the mail editor from the mailto link, and then put the window.onbeforeunload = function(){}; back?
Thanks
You could add a script like this after your anchor:
Mail
<script>
(function(w, d){
var anchors = d.getElementsByTagName('a');
var a = anchors[anchors.length - 1];
a.onclick = function(){
var old_unload = w.onbeforeunload;
w.onbeforeunload = null;
w.location = a.href;
setTimeout(function(){
w.onbeforeunload = old_unload;
}, 0);
return false;
};
})(window, document);
</script>
JSFiddle Demo
Note: The first revision did not work, because w.onbeforeunload = old_unload was running before the browser changed to the mailto page. Using setTimeout to make the assignment asynchronous solves that problem.

Issue due to iframe

I am having two radio buttons(traverse and direct) in a jsp form.Traverse for submitting form normally and Direct for sumbitting the form using iframe.After submitting the form using iframe ,if i try to submit normally,the application is opening in new window.How to prevent the form from opening in new window.
function submitAction() {
var fileValue = document.getElementById("file1").value;
if (fileValue == "") {
alert("Please uploaded file type of .war or .html type");
return false;
}
var valuePassed = getCheckedRadio();
var url="uploadfile.do?rad=" + valuePassed;
if (valuePassed == "traverse") {
document.EntryForm.action = url;
document.EntryForm.submit(); //Normal way of submitting.
}else if (valuePassed == "direct") {
alert("direct");
url=url+"&fileName="+fileValue;
directConvert(document.EntryForm,url,'downloaddiv'); }
}
function directConvert(form, action_url, div_id){
// Create the iframe...
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "upload_iframe");
iframe.setAttribute("name", "upload_iframe");
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("border", "0");
iframe.setAttribute("style", "width: 0; height: 0; border: none;");
// Add to document...
form.parentNode.appendChild(iframe);
//window.frames['upload_iframe'].name = "upload_iframe";
iframeId = document.getElementById("upload_iframe");
// Add event...
var eventHandler = function () {
if (iframeId.detachEvent) iframeId.detachEvent("onload", eventHandler);
else iframeId.removeEventListener("load", eventHandler, false);
// Message from server...
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
} else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
} else if (iframeId.document) {
content = iframeId.document.body.innerHTML;
}
document.getElementById(div_id).innerHTML = content;
// Del the iframe...
setTimeout('iframeId.parentNode.removeChild(iframeId)',50);
}
if (iframeId.addEventListener) iframeId.addEventListener("load", eventHandler, true);
if (iframeId.attachEvent) iframeId.attachEvent("onload", eventHandler);
// Set properties of form...
form.setAttribute("target", "upload_iframe");
form.setAttribute("action", action_url);
form.setAttribute("method", "post");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("encoding", "multipart/form-data");
form.submit();
}
when i try traverse first time it is working properly but after submitting through iframe,if i try traverse it is opening in new window.How to prevent it from opening in New window.
Because you are passing the form object of EntryForm to the iframe and changing the form.setAttribute("target", "upload_iframe"); while doing a directConvert submit.
So the form target remains so even when you try to submit through traverse but since the iframe is removed (setTimeout('iframeId.parentNode.removeChild(iframeId)',50);) from the page it opens in a new window after submit instead of the iframe.
So you can change back the target to _self in traverse submit: document.EntryForm.target = "_self".
By the way target attribute is deprecated in HTML 4.01.

Categories

Resources