Onclick display in the same page or same tab - javascript

I have Javascript as below:
<script type="text/javascript" language="javascript">
function redirectToPrevious(abcURL)
{
window.location.replace(abcURL);
}
function redirectToNext(xyzURL)
{
window.location.replace(xyzURL);
}
</script>
<input type="button" value="submit" onclick="redirectToNext('<%=abcURL>');"/>
In the above Javascript, I want the URL passed which is abcurl to displayed in the same tab/page where submit button is clicked. For certain URLs get invoked or displayed under same tab in window, but for certain URLs it gets displayed in a new tab. What might be the problem?
Can anyone help me on this?

And what is the difference in these urls ? - are perhaps some of them in a different zone (thinking ie security settings here). Also how is the javascript invoked - e.g. from an anchor tag, or a button etc.

Related

How do I make a browser return to the *last* version of my page when using the back button?

I have a dynamic web page foo.html. The user can interact with various controls, which modify various parts of the page.
When the user leaves the page and later returns with the browser's back button, the user is returned to the initial version of the page. What do I need to do to make the user return to the final version of the page?
Here's a minimal example to reproduce the issue:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button id="btnDo">Do something</button>
<!-- Imagine lots of other controls to dynamically create content here. -->
<span id="someContent"></span>
<!-- Imagine lots of other fields showing dynamically created content here. -->
Leave
<script type="text/javascript">
$(function () {
$("#btnDo").click(function () { $("#someContent").text(new Date()); });
});
</script>
Click on "Do something".
Note that the current date and time is displayed.
Click on "Leave".
Click the browser back button (in the snippet, use the context menu).
Desired result: The date and time created in step 2 should still be shown.
Actual result: The initial version of the page is shown.

Unexpected web page refresh in Chrome browser

I've been facing this weird behavior for a while now and can't find any workaround.
There is a button with certain methods called on click.
In Firefox works well. In Chrome it just refreshes the whole page.
$("#modoComparativa").click(function(){
if($(this).hasClass("active")){
$('#histFromDate').attr("placeholder","Date 1");
$('#histToDate').attr("disabled","disabled").attr("placeholder","Date 2");
startDatepickerComp();
}
else{
$('#histFromDate').attr("placeholder","Initial date");
$('#histToDate').attr("disabled","disabled").attr("placeholder","Final date");
startDatepicker();
}
$('#clearDates').attr("disabled","disabled");
// This function calls another function causing the odd behavior in Chrome
requestGraph(idDetail, idArea, "", "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If I comment out everything but the selector and the call to the click method, the behavior is the same. It refreshes everything.
I can't figure out how to debug this as each time I press the button, the whole page refreshes and no log/errors remains in the browser debugger.
Any ideas would be appreciated.
Edit - Addition of the selector as requested:
<div class="form-group"><button class="tooltip3 btn btn-default glyphicon glyphicon-random" id="modoComparativa" data-toggle="tooltip" title="ACTIVAR COMPARATIVAS" data-placement="bottom"></button>
</div>
Add a return false to your click callback to prevent actions due to your html syntax (like form submission or clicking on a anchor tag).
$("#modoComparativa").click(function(event){
event.preventDefault();
// your existing code
}
Edit: Since you added your html...
If your button is within a form, you can also add the type="button" attribute to prevent it from submitting your form.
<button type="button" class="tooltip3 btn btn-default glyphicon glyphicon-random" id="modoComparativa" data-toggle="tooltip" title="ACTIVAR COMPARATIVAS" data-placement="bottom"></button>
Thank you to lonesomeday for suggesting http://api.jquery.com/event.preventDefault/
I added an answer which could be useful for people stumbling here but having other causes for this behavior.
This kind of unexpected random reload can be due to several causes:
As stated in other answers a link which propagates the click and then performs a GET on the page itself
An image tag <img> where the src is empty or invalid, the browser will attempt to load the image using GET, but will in fact refresh the page instead (empty = relative to the page = page). Even a hidden image will be loaded, so this can be tricky to find, use the browser console !
Some javascript logic which refreshes the page programmatically in some conditions (session expired, token expired ...)
A browser 'feature', for example: https://support.mozilla.org/en-US/questions/1204335, or https://superuser.com/questions/1048029/disable-auto-refresh-tabs-in-chrome-desktop
In any case use the browser console and look for suspect GET calls to the page itself or redirects.

Difference between button onclick and a href

I'm trying to integrate SendOwl shopping cart into my application (details of the application are at the end).
To demo the problem I created a simple snippet using pure HTML / Javascript. In the head section of the HTML, I have this:
<script type="text/javascript">
function SendOwl(url) {
window.location.href=url;
}
</script>
<script type="text/javascript" src="https://transactions.sendowl.com/assets/sendowl.js" ></script>
In the body I have this:
Example 1: Opens the checkout form in its own window (Undesired behavior):
<input type="button" onclick="SendOwl('https://transactions.sendowl.com/products/8/5C080C0F/purchase');" value="On Click" />
Screenshot 1: Notice the URL changed and it's not an overlay (compared to 2).
Example 2: Opens the checkout form in a modal window as an overlay (Desired behavior):
<a href='https://transactions.sendowl.com/products/8/5C080C0F/purchase'>a href</a>
Screenshot 2: The URL stays the same, but the form opens in an overlay.
You can also see a live demo on the SendOwl's demo page.
My application is based on GWT (SmartGWT to be precise). In my application, I call button onclick handler to invoke a Javascript that invokes the Buy Now link using JSNI call (shown below). But the Buy Now link always opens in a full window as in example 1 above.
public static native void onBuyNowClick(String url) /*-{
$wnd.SendOwl(url);
}-*/;
I have tried $wnd.open(url) but that has the same behavior.
How do I get the first example to behave like the second but still using button onclick?
UPDATE:
The magic is in the sendowl.js script. If I remove that script, then both examples work the same way. If I could figure out how that script works, it might give some clues to make Example 1 work the same way as Example 2.
Thanks.
I have resolved the issue myself by probing into the sendowl.js . That's the script which is doing all the magic.
This is my modified script that makes Example 1 work exactly like Example 2:
<script>
function SendOwl(url) {
sendOwl.addLoadingImage();
sendOwl.loadIframe ('https://transactions.sendowl.com/products/8/5C080C0F/purchase');
}
</script>
<script src="https://transactions.sendowl.com/assets/sendowl.js"></script>
Thanks to all who replied and tried to help.
All you need is:
<script type="text/javascript" src="https://transactions.sendowl.com/assets/sendowl.js" ></script>
<input type="button" value="Purchase" />
https://help.sendowl.com/help/article/link/button-codes-to-sell-your-product
Works fine for me.
In GWT you can use a PopupPanel to display the overlay. Personally I never tried embedding a page inside a popup but you can try adding a Frame object inside the popup panel, something like this:
PopupPanel popup = new PopupPanel();
Frame frame = new Frame("http://www.yourlink.com/");
popup.setWidget(frame);
popup.setGlassEnabled(true);
popup.center();
As for the URL please check the documentation and this thread

Can I use JavaScript that is called on page load to modify other elements on the page?

I work in advertising. I have a client who has a tracking tag implemented on page load on their advertiser's site. The tracking tag is just a script that calls the JavaScript contained within.
The client is running into a dilemma because they want to trigger another tag when a specific button on the page is clicked on. I don't know the reasoning, but the advertiser's web developers said that it would take them weeks to make the change and the client is aiming to get the tracking set up as soon as possible.
The client's only means of access to the advertiser's page is through the tracking tag called on page load. The client wants to call some JavaScript from the tag that fires on page load that executes a certain function with the button is clicked on. I guess this would involve writing some JavaScript to the document so that it is usable when the button is clicked on.
Questions:
1) Is this possible? In other words, can I take some JavaScript that executes on page load and use it to modify elements on the page?
2) If the button already has another onclick function attached, can we add a second one? The button has a 'class' attribute attached, so could I develop some JavaScript to search for that class attribute and append a second onclick to it? Or would that override the first one?
Note: I cannot use document.write. Would document.appendchild work? Any tips would be appreciated.
To clarify what I want to do again:
1) Trigger JavaScript file on page load.
2) From within that JavaScript file, send a function to the document/page, and attach the reference to that function to a button with a specific class attribute on the page via an onclick attribute.
3) I do not want to override any existing onclick function on the button.
Thanks,
Update:
Here's what I have so far.
<html>
<head>
<script>
function myFunction (){
//do something
}
document.getElementsByClassName('test').onclick = myFunction();
</script>
</head>
<body>
<button class="test"> Submit Request </button>
</body>
</html>
I want to make it so that when the script in the header loads, myFunction is called from the button with class "test". Am I on the right track?
Update 2: Would using setAttribute work?
<html>
<body>
<script>
function myFunction (){
//do something
}
document.getElementsByClassName('test')[0].setAttribute("onclick", "myFunction()");
</script>
<button class="test"> Submit Request </button>
</body>
</html>

History object back button with iframes

I'm having problems with history object and iframes in javascript/html5. I wrote a simple project to describe my problem:
http://dktest.evermight.com/
It's a page with an iframe and a next button. Every time you click next, it loads a new page with an incrementing counter. However, clicking the browser back button doesn't do what I want it to do. Let me explain the problem by breaking this post up into the following sections:
What I'd like to achieve
Undesired results in current project
Post all my code
1. What I'd like to achieve
I want the user to:
Open a new window and go to http://dktest.evermight.com/
Click next page and see a redbox fade in, and to see the url http://dktest.evermight.com/count.html?count=0 appear in both the iframe AND the browser's address bar
Click next page again and see http://dktest.evermight.com/count.html?count=1 in the iframe and browser's address bar
Click browser's back button ONCE and see http://dktest.evermight.com/count.html?count=0 in both the iframe and the browser's address bar
Click browser's back button ONCE and see http://dktest.evermight.com/ in the browser's address bar AND see the red box fade out
2. Undesired results in current project
With my code at http://dktest.evermight.com/, it's currently not performing steps 4 and steps 5 correctly. When I perform step 4, the iframe shows http://dktest.evermight.com/count.html?count=0 but the browser address bar shows http://dktest.evermight.com/count.html?count=1. I have to press the browser's back button again to make the browser address bar show http://dktest.evermight.com/count.html?count=0. When I perform step 5, the red box fades out which is great, but the address bar is still showing http://dktest.evermight.com/count.html?count=0. I have to press back again to make the address bar show http://dktest.evermight.com/.
3. Post all my code
My code is pretty straight forward. You can view source on http://dktest.evermight.com/. I will also post here for convenience.
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var count=0;
function clicknext()
{
$('#container').fadeIn();
$('#iframe').attr('src','count.html?count='+count.toString());
$('html title').html(count);
history.pushState({blahblah:'whatgoeshere?'},'i dont know what goes here either','http://dktest.evermight.com/count.html?count='+count);
count++;
}
function hideContainer()
{
$('#container').fadeOut();
var closeurl = 'close.html';
if($('#iframe').attr('src') != closeurl )
$('#iframe').attr('src', closeurl);
}
$(document).ready(function(){
hideContainer();
});
</script>
</head>
<body>
<div id="container" style="display:none; background:red;">
<!-- IMPORTANT
When DOM first created, the iframe.src MUST BE initialize.html
I have some code that I need to fire on that page before the rest
of this document starts
-->
<iframe id="iframe" src="initialize.html"></iframe>
</div>
<input type="button" onclick="clicknext()"; value="next page" />
</body>
</html>
close.html
<!DOCTYPE html>
<html>
<script type="text/javascript">
parent.hideContainer();
</script>
</html>
count.html
I CAN NOT modify the contents of count.html. In my real project, count.html is actually a youtube video, which is on a server I can't directly access.
<html>
<body>Youtube video at url <script type="text/javascript">document.write(location.href);</script></body>
</html>
initialize.html
Perform application specific functionality
Can anyone correct my code to achieve the results of step 4 and step 5 as described in section 1?
UPDATE
Ok, I'm appreciating the problem a bit more based on some experiments I'm doing.
Experiment 1: I tried changing the line:
$('#iframe').attr('src','count.html?count='+count.toString());
to
$('#iframe')[0].contentWindow.location.replace('count.html?count='+count.toString());
This allowed me to perform step 4 correctly. Apparently, contentWindow.location.replace() will not create an entry in the history object. However, this caused some other issues related with the contents of count.html, which is actually a page to youtube/vimeo content. The youtube/vimeo content REQUIRES that you load information via the attr('src') approach instead of .contentWindow.location.replace(). So perhaps the solution is to find a way to make attr('src') NOT create an entry with the history object?
Experiment 2 Another possible solution I tried was changing the order of the attr('src') and history.pushState() call. I tried calling attr('src') first then history.pushState() second, and also history.pushState() first then attr('src') second. But in both cases, when I push the browser's back button, it is the iframe content that goes back first. So there's no way for me to capture pass myself a message via the history object to do a "double back", since information in the history object is available LAST in the sequence of events.
Experiment 3 I also tried working with History.js. It did not do anything to solve my problems above. From what I could tell, it worked exactly like the regular history object.
Does anyone have any thing else I can try? Or suggest modifications to any of the experiments above? I'm going to explore Experiment 1 further as a separate stack overflow question.
I create a new iframe and destroy the iframe when loading new content. That solves the history issues.
I know this is a history problem but if you are still open to other possibilities, I think jquery-pjax is actually more suitable for what you are trying to do.
UPDATE I think this should work.
count.html
<div id="pjax-container">
<a id="pjax" data-pjax href="#">Next Page</a>
</div>
javascript
// get URL parameter (count): http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
$(document).on('pjax:beforeSend', function() {
// your fading code goes here
})
$(document).on('pjax:complete', function() {
// fade out
// and then modify the anchor's href with something like
var new_count = getURLParameter('count') + 1;
$('a#pjax').attr('href', 'count.html?count=?' + new_count);
})
// where the pjaxed content should go
$(document).pjax('a[data-pjax]', '#pjax-container')

Categories