remove javascript form.setAttribute action - javascript

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.

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.

jQuery Image load() event return false not working?

I write a function for checking image height and width. You can find my code below. It works but I have a problem with return false: it does not work.
$("#published").click(function( event ){
var img = $('<img src="'+selectedImage+'"/>').load(function( event ){
var orgWidth = this.width;
var orgHeight = this.height;
console.log(orgWidth+" = "+orgHeight);
if(orgWidth >= 169 && orgHeight >= 169){
thisValidate.parent('div.rwmb-input').children('.imageError').remove();
return true;
}else{
event.preventDefault();
if(thisValidate.parent('div.rwmb-input').children('.imageError').length == 0){
thisValidate.parent('div.rwmb-input').append("<p class='imageError'></p>");
}
thisValidate.parent('div.rwmb-input').children('.imageError').html('<br/><label for="techranger_booked_feature_images" class="error">Upload Image More then 169 x 169</label>');
return false;
}
});
});
I have added event.preventDefault(); but it did not help as well.
You are returning to the load() function which isn't going to return to the outer click function.
Also load() is asynchronous so the click event will be completed long before load().
Finally you have 2 event arguments and the one inside load isn't going to have any impact on the click
You would need to prevent the click completely and trigger the next event manually when the load() succeeds.
$("#published").click(function( event ){
event.preventDefault();// prevent default
// no access to "this" inside load() so store reference to form
var $form = $(this).closest('form');
var img = $('<img src="'+selectedImage+'"/>').load(function(imgEvt ){
// code removed for clarity
if(orgWidth >= 169 && orgHeight >= 169){
/* trigger form submit */
$form.submit();
}else{
// other code
}
});
});
Firstly, your return false is running in the scope of the function which serves the load event and your event is an event of jQuery load function.
Secondly, if you want to do it on the button, you cannot do it synchronously like you try to do because the request to get your image is asynchronous, so it happens after your function on button event is finished (so you can't stop the event default behavior because it is already happened). You are forced to prevent / return false in the click method regardless of the image size and then call another function when the check is (un-?)successful to go on. This is the only way.
$("#published").click(function(event){
// here your check, e.g. if (imageFits) goOnFunction();
event.preventDefault();
});
And finally you absolutely do not need jQuery here:
var myImage = new Image();
myImage.src = 'http://okolo.me/wp-content/uploads/2015/07/5998.jpg';
myImage.onload = function() {
// here you can use myImage.width and myImage.height
};

How to identify a browser close event in javascript [duplicate]

I want to capture the browser window/tab close event.
I have tried the following with jQuery:
jQuery(window).bind(
"beforeunload",
function() {
return confirm("Do you really want to close?")
}
)
But it works on form submission as well, which is not what I want. I want an event that triggers only when the user closes the window.
The beforeunload event fires whenever the user leaves your page for any reason.
For example, it will be fired if the user submits a form, clicks a link, closes the window (or tab), or goes to a new page using the address bar, search box, or a bookmark.
You could exclude form submissions and hyperlinks (except from other frames) with the following code:
var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });
$(window).on("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
For jQuery versions older than 1.7, try this:
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
The live method doesn't work with the submit event, so if you add a new form, you'll need to bind the handler to it as well.
Note that if a different event handler cancels the submit or navigation, you will lose the confirmation prompt if the window is actually closed later. You could fix that by recording the time in the submit and click events, and checking if the beforeunload happens more than a couple of seconds later.
Maybe just unbind the beforeunload event handler within the form's submit event handler:
jQuery('form').submit(function() {
jQuery(window).unbind("beforeunload");
...
});
For a cross-browser solution (tested in Chrome 21, IE9, FF15), consider using the following code, which is a slightly tweaked version of Slaks' code:
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind('beforeunload', function(eventObject) {
var returnValue = undefined;
if (! inFormOrLink) {
returnValue = "Do you really want to close?";
}
eventObject.returnValue = returnValue;
return returnValue;
});
Note that since Firefox 4, the message "Do you really want to close?" is not displayed. FF just displays a generic message. See note in https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload
window.onbeforeunload = function () {
return "Do you really want to close?";
};
My answer is aimed at providing simple benchmarks.
HOW TO
See #SLaks answer.
$(window).on("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
How long does the browser take to finally shut your page down?
Whenever an user closes the page (x button or CTRL + W), the browser executes the given beforeunload code, but not indefinitely. The only exception is the confirmation box (return 'Do you really want to close?) which will wait until for the user's response.
Chrome: 2 seconds.
Firefox: ∞ (or double click, or force on close)
Edge: ∞ (or double click)
Explorer 11: 0 seconds.
Safari: TODO
What we used to test this out:
A Node.js Express server with requests log
The following short HTML file
What it does is to send as many requests as it can before the browser shut downs its page (synchronously).
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function request() {
return $.ajax({
type: "GET",
url: "http://localhost:3030/" + Date.now(),
async: true
}).responseText;
}
window.onbeforeunload = () => {
while (true) {
request();
}
return null;
}
</script>
</body>
</html>
Chrome output:
GET /1480451321041 404 0.389 ms - 32
GET /1480451321052 404 0.219 ms - 32
...
GET /hello/1480451322998 404 0.328 ms - 32
1957ms ≈ 2 seconds // we assume it's 2 seconds since requests can take few milliseconds to be sent.
For a solution that worked well with third party controls like Telerik (ex.: RadComboBox) and DevExpress that use the Anchor tags for various reasons, consider using the following code, which is a slightly tweaked version of desm's code with a better selector for self targeting anchor tags:
var inFormOrLink;
$('a[href]:not([target]), a[href][target=_self]').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind('beforeunload', function(eventObject) {
var returnValue = undefined;
if (! inFormOrLink) {
returnValue = "Do you really want to close?";
}
eventObject.returnValue = returnValue;
return returnValue;
});
I used Slaks answer but that wasn't working as is, since the onbeforeunload returnValue is parsed as a string and then displayed in the confirmations box of the browser. So the value true was displayed, like "true".
Just using return worked.
Here is my code
var preventUnloadPrompt;
var messageBeforeUnload = "my message here - Are you sure you want to leave this page?";
//var redirectAfterPrompt = "http://www.google.co.in";
$('a').live('click', function() { preventUnloadPrompt = true; });
$('form').live('submit', function() { preventUnloadPrompt = true; });
$(window).bind("beforeunload", function(e) {
var rval;
if(preventUnloadPrompt) {
return;
} else {
//location.replace(redirectAfterPrompt);
return messageBeforeUnload;
}
return rval;
})
Perhaps you could handle OnSubmit and set a flag that you later check in your OnBeforeUnload handler.
Unfortunately, whether it is a reload, new page redirect, or browser close the event will be triggered. An alternative is catch the id triggering the event and if it is form dont trigger any function and if it is not the id of the form then do what you want to do when the page closes. I am not sure if that is also possible directly and is tedious.
You can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
/* Do you small action code here */
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload
jQuery(window).bind("beforeunload", function (e) {
var activeElementTagName = e.target.activeElement.tagName;
if (activeElementTagName != "A" && activeElementTagName != "INPUT") {
return "Do you really want to close?";
}
})
If your form submission takes them to another page (as I assume it does, hence the triggering of beforeunload), you could try to change your form submission to an ajax call. This way, they won't leave your page when they submit the form and you can use your beforeunload binding code as you wish.
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()
$(window).bind("beforeunload", function() {
return true || confirm("Do you really want to close?");
});
on complete or link
$(window).unbind();
Try this also
window.onbeforeunload = function ()
{
if (pasteEditorChange) {
var btn = confirm('Do You Want to Save the Changess?');
if(btn === true ){
SavetoEdit();//your function call
}
else{
windowClose();//your function call
}
} else {
windowClose();//your function call
}
};
My Issue: The 'onbeforeunload' event would only be triggered if there were odd number of submits(clicks). I had a combination of solutions from similar threads in SO to have my solution work. well my code will speak.
<!--The definition of event and initializing the trigger flag--->
$(document).ready(function() {
updatefgallowPrompt(true);
window.onbeforeunload = WarnUser;
}
function WarnUser() {
var allowPrompt = getfgallowPrompt();
if(allowPrompt) {
saveIndexedDataAlert();
return null;
} else {
updatefgallowPrompt(true);
event.stopPropagation
}
}
<!--The method responsible for deciding weather the unload event is triggered from submit or not--->
function saveIndexedDataAlert() {
var allowPrompt = getfgallowPrompt();
var lenIndexedDocs = parseInt($('#sortable3 > li').size()) + parseInt($('#sortable3 > ul').size());
if(allowPrompt && $.trim(lenIndexedDocs) > 0) {
event.returnValue = "Your message";
} else {
event.returnValue = " ";
updatefgallowPrompt(true);
}
}
<!---Function responsible to reset the trigger flag---->
$(document).click(function(event) {
$('a').live('click', function() { updatefgallowPrompt(false); });
});
<!--getter and setter for the flag---->
function updatefgallowPrompt (allowPrompt){ //exit msg dfds
$('body').data('allowPrompt', allowPrompt);
}
function getfgallowPrompt(){
return $('body').data('allowPrompt');
}
Just verify...
function wopen_close(){
var w = window.open($url, '_blank', 'width=600, height=400, scrollbars=no, status=no, resizable=no, screenx=0, screeny=0');
w.onunload = function(){
if (window.closed) {
alert("window closed");
}else{
alert("just refreshed");
}
}
}
var validNavigation = false;
jQuery(document).ready(function () {
wireUpEvents();
});
function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function () {
debugger
if (!validNavigation) {
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function (e) {
debugger
if (e.keyCode == 116) {
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function () {
debugger
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function () {
debugger
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function () {
debugger
validNavigation = true;
});
}`enter code here`
Following worked for me;
$(window).unload(function(event) {
if(event.clientY < 0) {
//do whatever you want when closing the window..
}
});

Detecting a form.submit() performed via JavaScript

In my page there is a frame that belongs to the same domain. The content of this frame is varied and relatively unpredictable. Whenever a user clicks a button (inside the frame) that performs a post, I need to execute a function that performs some UI tasks. The problem is that I cannot edit the source of these frames for reasons beyond my control. Some of these buttons are simple form submit buttons, but others do not directly submit the form, but instead have an onclick handler that performs some checks and might submit.
Here is the problem: How do I detect if one of these onclick handlers called form.submit()? If there's no handler, then obviously I can set up a handler for onsubmit(), but is not the case for all of these buttons.
This is my code so far:
function addEventBefore(element, type, before, after) {
var old = element['on' + type] || function() {};
before = before || function() {};
after = after || function() {};
element['on' + type] = function () {
before();
old();//I can't modify this old onclick handler
after();
};
}
function setup() {
console.log('setup');
}
function takedown() {
// In this method, I want to know if old() caused a form submit
console.log('takedown');
}
function $includeFrames(jQuery, selector) {
return jQuery(selector).add(jQuery('iframe').contents().find(selector));
}
var a = $includeFrames($, 'input[type="submit"], input[type="button"]').each(function() {
var elem = $(this)[0];
addEventBefore(elem, 'click', setup, takedown);
});
In the onload event of the iframe you'll need to hook up an event listener to each form in the iframed page. You need to do this on every load, as each fresh page needs new listeners.
$("#someIframe").on('load',function() {
$(this).contents().find("form").each(function() {
$(this).on('submit',function() {... your code...})
})
}
The solution that worked for me came from a friend of mine. The solution is to shim the form.submit() function.
$(function() {
var el = document.getElementById('myform');
el.submit = function(fn) {
return function() {
myFunctionGoesHere();
fn.apply(this, arguments);
};
}(el.submit);
});
Here is a working example: http://jsfiddle.net/hW6Z4/9/

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

Categories

Resources