Form Submit onbeforeunload in Firefox - javascript

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.';
};

Related

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

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.

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.

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.

Dynamic multiple location form submit with javascript

I'm trying to write some JavaScript for my website that will select all the forms on a page, add an event listener for when they are submitted, and then route the values submitted to the main action page and an additional alternate page.
Here's what I have so far:
Send.php:
<script type="text/javascript">
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
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); // Not entirely sure if this is necessary
form.submit();
}
function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
}
else if (elm.attachEvent) {
var r = elm.attachEvent('on' + evType, fn);
return r;
}
else {
elm['on' + evType] = fn;
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
}
else {
window.onload = function() {
oldonload();
func();
}
}
}
function addSubmits() {
var fs=document.forms;
for(var i=0;i<fs.length;i++){
//addEvent(fs[i],"submit",post_to_url('http://www.gwtwg.com/recieve.php', {'email' : 'test.com'}), false)
}
}
addLoadEvent(addSubmits);
</script>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<input type="text" name="email" />
<input type="submit" value="Submit!" />
</form>
Right now the script just freezes up, but if I replace: "post_to_url('http://www.gwtwg.com/recieve.php', {'email' : 'test.com'})"
with:
"alert("foobar")"
I get an alert when I load the page and when the form is submitted. (It should only occur when the button is submitted).
Any thoughts on whats wrong?
So, the problem here is really that you're not using any JS library. Personally I would recommend that you use jQuery, but any of the major ones will work. All of the functions you showed have more robust equivalents in the various JS libraries, so it's silly to try and debug them when you can just replace them with better-tested, more robust versions, for free.
If you were using jQuery, here's how (I think) you could do what you want to do:
var URL = "http://www.gwtwg.com/recieve.php"; // Define your site's URL
$(function() { // setup an onReady (similar to onLoad) handler
$("form") // get all forms on the page
.submit(function() { // hook up an onSubmit handler to them
var params = $(this).serialize(); // get this form's data
$.post(URL, paprams);// POST the data your server
});
});
Now, I haven't actually tested any of that, but it should work (and even if it doesn't, hopefully you get the idea). Also, notice how much shorter it is? Yet another benefit. The important thing though is, if you use established code, that's been reviewed by hundreds of eyeballs, you won't spend time re-inventing the wheel. Also, far more importantly, you won't waste time begging people on the Internet to help you debug your version of that wheel ;-)

Categories

Resources