I have a JavaScript issue. I am using it to open an HTML web page in a new frame with the following function:
function openBranch(url) {
if (url == "Ping") {
top.folderFrame.location = "Ping.html"
} else if (url == "Logout") {
top.top.location = "Logout.html"
}
}
HTML usage:
<a href='javascript:openBranch("Ping")'>Ping</a>
I am unable to open another web page in my side menu bar once my Ping.html page is processed (Post request is used). My side menu bar is unable to open the new page and is not able to process any request.
It looks like the argument of the function changes the source of the document. If you want to just change the source, why don't you just do something like this:
<iframe src="test1.html" id="top"></iframe>
change to 1
change to 2
<script>
function change(val) {
if (val === 1) {
document.getElementById("top").src = "test1.html";
} else {
document.getElementById("top").src = "test2.html";
}
}
</script>
Related
We have a Lottie animation that should act as a preloader and show only on the Home page.
We want to SHOW this when accessing the home page by:
clicking on a link from an external page (not on your website)
clicking refresh on the browser
when entering the URL in the browser's address bar.
We DON'T want to show the animation when
clicking on a link from an internal page (on your website)
navigate through the browser's prev/next history buttons.
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>
<div id="preloader">
<div class="logo" id="home-preloader"></div>
</div>
<style>
/* Some styling here */
</style>
<script>
function playPreloader() {
var animation = bodymovin.loadAnimation({
container: document.getElementById('home-preloader'),
path: 'preloader.json',
renderer: 'svg',
loop: false,
autoplay: true,
name: "Home Preloader",
});
}
</script>
Any ideas on how to do it? I tried a few things with PerformanceNavigation.type and PerformanceNavigationTiming.type but couldn't manage to figure it out. I'm not very skilled in JavaScript, but can manage things if I can have direction.
Even if this worked, it doesn't seem to differentiate between external and internal links.
window.addEventListener("load", function() {
var performance = window.performance || window.webkitPerformance || window.msPerformance || window.mozPerformance;
var navigation = performance.getEntriesByType("navigation")[0];
if (navigation.type === "navigate") {
console.log("The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.");
}
else if (navigation.type === "reload") {
console.log("The page was accessed by clicking the Reload button or via the Location.reload() method.");
playPreloader();
yesPreloader();
}
else if (navigation.type === "back_forward") {
console.log("The page was accessed by navigating into the history.");
noPreloader();
}
else {
console.log("Any other way.");
}
});
After researching for two days, I found a comment that was very helpful and helped me create a working solution to my problem. Here's the code for anyone having the same problem.
If somebody can confirm that all of this is correct, that would be nice.
/* (0) WHEN THE PAGE IS LOADED */
window.addEventListener("load", function() {
/* (1) FIND HOW THE PAGE WAS ACCESSED */
var result;
var p;
if (window.performance.navigation) {
result = window.performance.navigation;
// 255
if (result == 255) {
result = 4
}
}
if (window.performance.getEntriesByType("navigation")) {
p = window.performance.getEntriesByType("navigation")[0].type;
// Page was accessed from a link or address bar
if (p == 'navigate') {
result = 0
}
// Page was reloaded (browser reload operation)
if (p == 'reload') {
result = 1
}
// Back or Forward (browser history)
if (p == 'back_forward') {
result = 2
}
// Prerender
if (p == 'prerender') {
result = 3
}
}
console.info(result);
/* (2) WHAT TO DO IN EACH CASE */
if (result == 0) {
// Page was accessed from a link or address bar
console.info("Page was accessed from a link or address bar");
console.info("Result was 0, result=" + result);
// Was it an internal link or (external link or address bar)
if (document.referrer.indexOf(location.hostname) !== -1) {
// Page was accessed from an internal link
console.info("Page was accessed from an internal link");
$(document).ready(function() {
noPreloader();
});
} else {
// Page was NOT accessed from internal link
// Probably accessed from external link or address bar
console.info("Page was NOT accessed from internal link. Probably accessed from an external link or address bar");
$(document).ready(function() {
$(this).scrollTop(0);
document.body.classList.add("overflow-x-hidden");
document.body.classList.add("overflow-y-hidden");
playPreloader();
yesPreloader();
});
}
} else if (result == 1) {
// Page was reloaded (browser reload operation)
console.info("Page was accessed by reloading (browser reload operation)");
console.info("Result was 1, result=" + result);
$(document).ready(function() {
$(this).scrollTop(0);
document.body.classList.add("overflow-x-hidden");
document.body.classList.add("overflow-y-hidden");
playPreloader();
yesPreloader();
});
} else if (result == 2) {
// Back or Forward (browser history)
console.info("Page was accessed from the browser history back or forward buttons");
console.info("Result was 2, result=" + result);
$(document).ready(function() {
noPreloader();
});
} else {
// Any other instance
console.info("Page was accessed: Any other instance (prerender or 255)");
console.info("Result was probably 255 (4) or prerender (3), result=" + result);
$(document).ready(function() {
noPreloader();
});
}
});
/* [END OF] (1) WHEN THE PAGE IS LOADED */
I'm making a system that uses authorization through an external API (VK). When the user clicks on "authorize via VK", they get a popup window where they can choose whether to grant permissions or cancel. Whatever they choose, the API just redirects them to my php script in the same popup window, and when that script is done, they are ending up with an empty popup window still open.
I need to do 2 things:
1) Close the popup window after the script is done.
2) Depending on what the function in the script returns, display the appropriate message for the user, not in that popup window, but in the initial window that initiated the popup (somewhere between the lines of the already existing text), after the popup has already closed.
Now, I don't know how to do this. There must me some javascript (preferrably jquery) that inserts a message to the initial window depending on the response obtained from the function that was called in a popup window that has already closed.
Here are some excerpts from the system:
http://example.com/vkcode?error=access_denied&error_reason=user_denied&error_description=User+denied+your+request&state=secret_state_code - this is the page the user gets redirected to (inside the popup) if they choose "cancel". And they keep staying on the blank page with that string in their address bar.
Here is some PHP code that handles the response from VK API:
public function vkAuthHandler() {
if (isset($_GET['error'])) {
if ($_GET['error_reason'] == 'user_denied' {
return 'user_denied';
}
else return 'error';
}
else {
// ... haven't written other logic yet, it's irrelevant anyway
}
return new Response();
}
Now, if I receive 'user_denied' response, I need to display a message telling the user that they refused the permissions. But not in that popup window where that function was called (it should already be closed by the time), but on the initial page, without reloading it.
I solved it in a sophisticated way. Not going to accept this answer because maybe someone offers a simplier solution.
In PHP:
public function vkAuthHandler() {
if (isset($_GET['error'])) {
if ($_GET['error_reason'] == 'user_denied' {
header('Set-cookie: vkresp=user_denied');
}
else header('Set-cookie: vkresp=error');
}
else {
// ...
}
echo "<script>window.close();</script>"; //closing the window here
return new Response();
}
In JavaScript (used jQuery and JS-Cookie), based on this solution:
var cookieRegistry = [];
function listenCookieChange(cookieName, callback) {
setInterval(function() {
if (cookieRegistry[cookieName] || Cookies.get(cookieName) != null) {
if (Cookies.get(cookieName) != cookieRegistry[cookieName]) {
cookieRegistry[cookieName] = Cookies.get(cookieName);
return callback();
}
} else {
cookieRegistry[cookieName] = Cookies.get(cookieName);
}
}, 100);
}
listenCookieChange('vkresp', function() {
if (Cookies.get('vkresp') == 'user_denied') {
console.log('VK response is user_denied');
$("#VKauth").append('<div style="color: red;">You denied authorization! Comments are blocked!</div>');
}
else if (Cookies.get('vkresp') == 'error') {
console.log('VK response is user_denied');
$("#VKauth").append('<div style="color: red;">Unknown authorization error. Try again.</div>');
}
Cookies.remove('vkresp');
});
$("#VKauth") is basically selecting an HTML element with the id VKauth on my page.
I would like to know how to load JavaScript file after loading of page via AJAX?
The problem is:
I have music player which uses JS file whith infomation about tracks.
After that I load page all works nice. But when I load another page via AJAX my script doesn't work at page which I called.
Code looks like this:
function showContent(link,link2) {
var cont = document.getElementById('content');
var loading = document.getElementById('loading');
window.history.replaceState('', 'Title', link2);
var http = createRequestObject();
if( http ) {
http.open('get', link);
http.onreadystatechange = function () {
if(http.readyState == 4) {
cont.innerHTML = http.responseText;
}
}
http.send(null);
} else {
document.location = link;
}
}
function createRequestObject() {
try { return new XMLHttpRequest() }
catch(e) {
try { return new ActiveXObject('Msxml2.XMLHTTP') }
catch(e) {
try { return new ActiveXObject('Microsoft.XMLHTTP') }
catch(e) { return null; }
}
}
}
Then I use angular-soundmanager2.js to make player alive.
And this cut of code won't work at page which I load after linking to this page
<h5>Songs</h5>
<ul>
<li ng-repeat="song in songs">
<button music-player="play" add-song="song">{{ song.title }}</button>
<button music-player add-song="song">+</button>
</li>
</ul>
<button play-all="songs">Play all</button>
<button play-all="songs" data-play="false">Add all</button>
It has to show me playlist. But I get nothing.
You must be binding the DOM element with javascript. On document ready you call something like this, $('#someDiv').makePlayer(). So, page loads it works fine. But when you make ajax, I guess you are replacing that page content on ajax. If you are removing and loading the DOM element again on which you called the makeplayer() earlier. You have to call makePlayer thing again after your ajax call.
I am playing with jquery and js, trying to build an ajax overlay image viewer for a PHP website. With this code included at the bottom of the 'gallery page', the viewer opens and i can navigate with next and previous links inside the viewer. But the back button and the history is hard to understand. The browser often shows only the response of the ajax call, without the underlying page and css files, after some clicks back.
Perhaps somebody knows what is generally happening in such a case? I would like to understand why back sometimes results in a broken page, i.e. only the ajax response.
<script type="text/javascript">
$(document).ready(function() {
function loadOverlay(href) {
$.ajax({
url: href,
})
.done(function( data ) {
var theoverlay = $('#flvr_overlay');
theoverlay.html( data );
var zoompic = $('#zoompic');
zoompic.load(function() {
var nih = zoompic.prop('naturalHeight');
var photobox = $('#photobox');
if($(window).width() >= 750){
photobox.css('height',nih);
}
theoverlay.show();
$('body').css('overflow-y','hidden');
$(window).resize(function () {
var viewportWidth = $(window).width();
if (viewportWidth < 750) {
photobox.css('height','auto');
zoompic.removeClass('translatecenter');
}else{
photobox.css('height',nih);
zoompic.addClass('translatecenter');
}
});
});
});
return false;
}
var inithref = window.location.href;
$(window).on('popstate', function (e) {
if (e.originalEvent.state !== null) {
//load next/previous
loadOverlay(location.href);
} else {
//close overlay
$('#flvr_overlay').hide().empty();
$('body').css('overflow-y','scroll');
history.replaceState(null, inithref, inithref);
}
});
$(document).on('click', '.overlay', function () {
var href = $(this).attr('href');
history.pushState({}, href, href);
loadOverlay(href);
return false;
});
});
</script>
edit
clicking forward works:
/photos (normal page)
/photos/123 (overlay with '/photos' below)
/locations/x (normal page)
/photos/567 (overlay with '/locations/x' below)
clicking back gives me the broken view at point 2.
Do you need to prevent the default behaviour in your popstate to prevent the browser from actually navigating back to the previous page?
you have to manage it by own code.
You have a few options.
Use localstorage to remember the last query
Use cookies (but don't)
Use the hash as you tried with document.location.hash = "last search" to update the url. You would look at the hash again and if it is set then do another ajax to populate the data. If you had done localstorage then you could just cache the last ajax request.
I would go with the localstorage and the hash solution because that's what some websites do. You can also copy and paste a URL and it will just load the same query. This is pretty nice and I would say very accessible
Changing to document.location.hash = "latest search" didn't change anything.t.
This goes into the rest of the jQuery code:
// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
if ('myTable' in localStorage && window.location.hash) {
$("#myTable").html(localStorage.getItem('myTable'));
}
}
// Save the search result table when leaving the page.
$(window).unload(function () {
if (('localStorage' in window) && window['localStorage'] !== null) {
var form = $("#myTable").html();
localStorage.setItem('myTable', form);
}
});
Another solution is that use INPUT fields to preserved while using back button. So, I do like that :
My page contains an input hidden like that :
Once ajax content is dynamicaly loaded, I backup content into my hidden field before displaying it:
function loadAlaxContent()
{
var xmlRequest = $.ajax({
//prepare ajax request
// ...
}).done( function(htmlData) {
// save content
$('#bfCache').val( $('#bfCache').val() + htmlData);
// display it
displayAjaxContent(htmlData);
});
}
And last thing to do is to test the hidden field value at page loading. If it contains something, that because the back button has been used, so, we just have to display it.
jQuery(document).ready(function($) {
htmlData = $('#bfCache').val();
if(htmlData)
displayAjaxContent( htmlData );
});
I have a feed from Coupons.com in the form of an iframe in my webpage and I want to run some JavaScript on this iframe. I want it to open on a page other than the default which is the first page.
If you go to http://www.coupons.com you can see the same feed I am working with.
Above the coupons is a list of pages 1-10. If you move the cursor over page 3 (for example) it reads javascript:GoToPage(3), which seems very simple, but I can't figure out how to script it and make that page 3 show up instead of page 1. Please help, thanks in advance-
they are reloading the page via ajax.
something like that (copied from another question that i answered):
HTML
JAVASCRIPT
function xmlhttp() {
var x;
try {
x = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {
try {
x = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
x = new XMLHttpRequest();
} catch (e) {
x = false;
}
}
}
return x;
}
function page(idMenu) {
var http = xmlhttp();
if (!http) {
alert('XmlHttpRequest non supporté');
} else {
var url = 'pageOutput.php?pageNo=' + idMenu;
http.open('GET', url, true);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
document.getElementById('pageContent').innerHTML = http.responseText;
}
}
http.send();
}
}
now all you have left to do is create a PHP where you check whatever menu ID is called and echo page content according to $_GET['pageNo']. if you already got your pages on many PHP/HTML you may also just do include and echo them...
if(isset($_GET['pageNo'])){
//echo page code here according to $_GET['pageNo'] value
}else{
//echo main page
}
EDIT: You may also add URL param to refer the current page so the user can reload your page from a new window without having no params loaded...
EDIT: Iframe version will just reload the whole iframe, if you look when you change page you see the iframe blink. i strongly recommand using a div content, much easyer.