How to get check if a page gets reloaded with js - javascript

How do you now check if a page gets reloaded?
It used to be like this:
//check for Navigation Timing API support
if (window.performance) {
console.info("window.performance works fine on this browser");
}
console.info(performance.navigation.type);
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
console.info( "This page is reloaded" );
} else {
console.info( "This page is not reloaded");
}
But now I found out that navigation type is deprecated:
https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation
So then I checked the replacement: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming
Even after reading it it's still not very clear on how I could accomplish this. So how does the new way work of checking if a page gets refreshed?
I also tried this after I had read it:
if (PerformanceNavigationTiming.type == "reload") {
alert('page reloaded')
}
But then the alert won't be displayed.
And after that I tried this:
if (PerformanceNavigationTiming.type == PerformanceNavigationTiming.TYPE_RELOAD) {
alert('page reloaded')
}
But then It would display the alert also without a page refresh.
Then the last thing I tried:
const pageAccessedByReload = (
(PerformanceNavigationTiming && PerformanceNavigationTiming.TYPE === 1) ||
window.performance
.getEntriesByType('navigation')
.map((nav) => nav.type)
.includes('reload')
);
alert(pageAccessedByReload);
But this also gives me an alert either false when it's not reloaded and true when it is reloaded. And I only want that alert when the page is reloaded.

You must remember to always pay attention when reading a new API docs, type in PerformanceNavigationTiming is a string and not a number so the correct way would be:
if (window.PerformanceNavigationTiming) {
console.info("window.performance works fine on this browser");
if (PerformanceNavigationTiming.type === "reload") {
console.info("This page is reloaded");
} else {
console.info("This page is not reloaded");
}
}

From MDN reference 2022: Navigation Timing Level 2 specification
const navigationType =
(window.performance.getEntriesByType('navigation')
[0] as PerformanceNavigationTiming).type;
const isPageReload = navigationType === 'reload';
const isNavigation = navigationType === 'navigate';
const isBackForwarad = navigationType === 'back_forward';
const isPrerender = navigationType === 'prerender';

I have finally found a solution:
const pageAccessedByReload = (
(PerformanceNavigationTiming && PerformanceNavigationTiming.TYPE === 1) ||
window.performance
.getEntriesByType('navigation')
.map((nav) => nav.type)
.includes('reload')
);
if (pageAccessedByReload == true) {
alert(pageAccessedByReload);
}
Now it will only show when the page is refreshed.

Related

Old JavaScript no longer working. Chrome says Event.path is deprecated, but I don't use Event.path in my code

I built a game of concentration over a year ago. I tried to run it today and when you click on the back of a "card" it's supposed to reveal a picture, but it does not. Chrome dev tools says "Event.path is deprecated and will be removed. Please use Event.composedPath() instead."
Nowhere in my code do I use Event.path and I can't seem to figure out what specifically is broken.
Here is the code I do have for a click event. The first function is repeated for all 24 cards and calls the second function which is supposed to reveal the picture "underneath" the back of the card and if both revealed pictures are the same they remain revealed, otherwise they both get reset to show the back of the card.
//onClick functions for all card images
pic1.onclick = () => {
console.log(revealedPics); //this sends the file link of the revealed picture to the console
if (isClicked(pic1) === false) {
pic1.src = picArray[0];
checkIfMatch(pic1);
} else if (trackRevealedCardsArray.includes(pic1.src) === true) {
return;
} else {
pic1.src = backOfCard;
}
console.log(revealedPics);
}
//Check if two revealed images are a match
const checkIfMatch = (pic) => {
if (revealedPics === 1) {
firstPic = pic;
} else if (revealedPics === 2) {
secondPic = pic;
if (firstPic.src === secondPic.src) {
revealedPics = 0;
totalPairs--;
trackRevealedCardsArray.push(firstPic.src);
console.log(`total pairs ${totalPairs}`);
if (totalPairs === 0) {
window.setTimeout(gameOver, 500);
}
} else {
window.setTimeout(function() {
firstPic.src = backOfCard;
secondPic.src = backOfCard;
}, 800);
window.setTimeout(resetRevealedPics, 800);
}
}
}
I've checked to make sure all my paths are correct and they are. When I run the same html files from my local drive it works perfectly.

How to capture the referring URL in a variable and then redirect to new page jquery or javascript

Almost have it, but might need a hand :
I created a script to redirect AND set a cookie that comes in from ANY page from our site. So even if a user comes in from a direct link to a news article, it will redirect them to our "splash" page and set a "cookie" to avoid further redirects. I have that part working perfect.
$(document).ready(function() {
if (typeof Cookies.get('secondvisit') === 'undefined') {
window.location.href = "/index-donate.php";
}
})
However, we now want to capture the URL that they came to first and create a variable so we can have them be linked back to that page after they read our SPLASH page.
So in the example above:
Come in via direct link: /news/article1.php
No cookie is detected, so we first need to "capture" the page they came in on "$page-refer" and then redirect them to our Splash page.
On the splash page, we would then present a LINK to them with "Proceed to webpage" with the "$page-refer" link.
I did try this ( BELOW ), but this is only grabbing the "google" page and not OUR webpage that they hit first.
Thanks!
$(document).ready(function() {
if (typeof Cookies.get('secondvisit') === 'undefined') {
var referringURL = document.referrer;
var local = referringURL.substring(referringURL.indexOf("?"), referringURL.length);
location.href = "/index-donate.php" + local;
}
})
I think you could add the URL as a cookie when you do the redirect, ex:
$(document).ready(function () {
if (typeof Cookies.get('secondvisit') === 'undefined') {
Cookies.set('initialvisitedpage', window.location.href);
window.location.href = "/index-donate.php";
}
});
then you could redirect them to the cookie value:
$(document).ready(function() {
if (typeof Cookies.get('secondvisit') === 'undefined') {
window.location.href = Cookies.get('initialvisitedpage') || '/'; // or whatever this could default to in case they don't have the cookie
}
})
Put together an answer that works great, thanks for the comments and push:
On footer script template:
$(document).ready(function () {
if (typeof Cookies.get('secondvisit') === 'undefined') {
location.href = "/index-donate.php?page-refer=" + encodeURIComponent(location.href);
}
})
Then on my Splash page:
I captured the variable $pageredirect via $_GET['page-refer'] and then presented that as a link further down the page ( if set )!

how toggle between two functions automatically without button

I want to toggle between interstitial ads and rewarded video ads in my game html use it construct 2 every time loading layout like if first runtime show interstitial and if loading again show rewarded video ads and repeat this every time .
SysActs.prototype.GoToLayout = function(to) {
showInterstitialAd();
showRewardedVideoAd();
if (this.runtime.isloading)
return; // cannot change layout while loading on loader layout
if (this.runtime.changelayout)
return; // already changing to a different layout
;
this.runtime.changelayout = to;
};
my testcode aftert toggle between two functions automatically
SysActs.prototype.GoToLayout = function (to)
{
if($(this).data('toggleAds') == 1) {
toggleAds = 0;
if (this.runtime.isloading || showRewardedVideoAd())
return;
if (this.runtime.changelayout )
return;
;
this.runtime.changelayout = to;
}
else {
toggleAds = 1;
if (this.runtime.isloading || showInterstitialAd() )
return;
if (this.runtime.changelayout )
return;
;
this.runtime.changelayout = to;
showInterstitialAd();
}
$(this).data('toggleAds', toggleAds);
return false;
};
i try this but is not work?
It doesn't work because you're not persisting anything on page reload, so you get the exact same page and same code, so the behaviour is exactly the same. You can't toggle this way. Store a state in the localStorage and read it on page load.
const previousState = localStorage.getItem("state"); // null, "interstitial" or "rewarded"
let currentState;
if(previousState){
currentState = previousState === "interstitial" ? "rewarded" : "interstitial";
} else { // First page load ever
currentState = "rewarded"; // or "interstitial", initialize it like you want
}
localStorage.setItem("previousState", currentState); // It's saved for next reload
// Now do something with currentState

JavaScript ignore alert if reloading page

I am detecting the end of a webrtc stream in JavaScript like this...
stream.getVideoTracks()[0].onended = () => {
alert('Feed Has Ended');
};
This is working correctly, but if the user refreshes or reloads the page then the alert is also shown.
I understand that this is technically correct, but how can I get it to not display the alert under those conditions?
Why don't you use a global boolean to check if video is playing or not? When you will reload or refresh the page, isVideoRunning will become false and alert won't show.
Like
this.isVideoRunning = false;
On addtrack,
this.rtcPeerCon_.ontrack = function (event) {
if (!this.rtcPeerCon_) {
return;
}
if( !this.remoteVideo_ ) {
return;
}
this.remoteVideo_.srcObject = event.streams[0];
this.isVideoRunning = true;
}
then in your onStream ended callback you can check
if (this.isVideoRunning) {
alert('whatever');
this.isVideoRunning = false;
}
(I wanted this to be comment but I am not allowed to comment yet)

Prestashop set catalog mode ON/OFF if user unlogged/logged

I'm working on a prestashop module to set the catalog mode ON or OFF if user is unlogged or logged.
Works great but got a problem.
I don't want unlogged users see prices at all and allowed to order. But with the solution I found, when first connection (mode catalog OFF) unlogged user load the page, the catalog mod turn ON, but he can see prices (has to reload to hide prices) So, first load set catalog mode ON and second load display real catalog mode.
I found a js script to reload automatically to take effect with the new mode but obviously, loading time of the page is two times longer.
Here is the function :
public function hookHeader()
{
$logged = $this->context->customer->isLogged();
if (!$logged) {
Configuration::updateValue('PS_CATALOG_MODE', true);
} else {
Configuration::updateValue('PS_CATALOG_MODE', false);
}
// reload the page once more
echo '
<script type="text/javascript">
(function() {
if( window.localStorage ) {
if( !localStorage.getItem( "firstLoad" ) ) {
localStorage[ "firstLoad" ] = true;
window.location.reload();
} else {
localStorage.removeItem( "firstLoad" );
}
}
})();
</script>
';
}
Hope somebody could help me with this. Thank you.
Your solution has a problem.
You're updating the value inside the database: if multiple users are browsing the site, the value will be turned on/off/on/off/..., in other words it's "unstable".
The next customer that visits the site will get the current value (can be on and off).
Instead, you should toggle the value only for that customer. I wrote an override for Configuration class, that check if you're trying to get PS_CATALOG_MODE, then check if you'er logged in and returns 0 or 1. Be careful to cache this value using static variables (so you don't have to check multiple times).
But this solution has a flaw too. It checks the key of the request configuration variable everytime.
A better solution would be to change the value of this during the session. Configuration variables are actually held in a PHP array during the session.
You should change it here:
https://github.com/PrestaShop/PrestaShop/blob/1.6.1.x/classes/Configuration.php#L203
possibly by overridding
https://github.com/PrestaShop/PrestaShop/blob/1.6.1.x/classes/Configuration.php#L140
This is what I had in mind by overriding loadConfiguration:
<?php
// placed in /override/classes/Configuration.php
class Configuration extends ConfigurationCore
{
public static function loadConfiguration()
{
parent::loadConfiguration();
// 'global' because I assume you're not runing multishop
self::$_cache[self::$definition['table']][0]['global']['PS_CATALOG_MODE'] = !Context::getContext()->customer->isLogged();
}
}
I wrote this from memeroy so be sure to check the anmes, etc. I assume you're running > PS1.6
Why don't you just use the group settings? Customer group settings allow you to set the "show prices" option to "false" for visitors, and "true" for customers, for example.
The solution we find with gskema is to override the get() function of the Configuration class :
<?php
// placed in /override/classes/Configuration.php
class Configuration extends ConfigurationCore
{
public static function get($key, $id_lang = null, $id_shop_group = null, $id_shop = null)
{
if (defined('_PS_DO_NOT_LOAD_CONFIGURATION_') && _PS_DO_NOT_LOAD_CONFIGURATION_) {
return false;
}
// If conf if not initialized, try manual query
if (!isset(self::$_cache[self::$definition['table']])) {
Configuration::loadConfiguration();
if (!self::$_cache[self::$definition['table']]) {
return Db::getInstance()->getValue('SELECT `value` FROM `'._DB_PREFIX_.bqSQL(self::$definition['table']).'` WHERE `name` = "'.pSQL($key).'"');
}
}
$id_lang = (int)$id_lang;
if ($id_shop === null || !Shop::isFeatureActive()) {
$id_shop = Shop::getContextShopID(true);
}
if ($id_shop_group === null || !Shop::isFeatureActive()) {
$id_shop_group = Shop::getContextShopGroupID(true);
}
if (!isset(self::$_cache[self::$definition['table']][$id_lang])) {
$id_lang = 0;
}
if ($id_shop && Configuration::hasKey($key, $id_lang, null, $id_shop)) {
if($key == 'PS_CATALOG_MODE' && Context::getContext()->controller->controller_type == 'front')
{
return !Context::getContext()->customer->isLogged() || self::$_cache[self::$definition['table']][$id_lang]['shop'][$id_shop][$key];
} else {
return self::$_cache[self::$definition['table']][$id_lang]['shop'][$id_shop][$key];
}
} elseif ($id_shop_group && Configuration::hasKey($key, $id_lang, $id_shop_group)) {
if($key == 'PS_CATALOG_MODE' && Context::getContext()->controller->controller_type == 'front')
{
return !Context::getContext()->customer->isLogged() || self::$_cache[self::$definition['table']][$id_lang]['group'][$id_shop_group][$key];
} else {
return self::$_cache[self::$definition['table']][$id_lang]['group'][$id_shop_group][$key];
}
} elseif (Configuration::hasKey($key, $id_lang)) {
if($key == 'PS_CATALOG_MODE' && Context::getContext()->controller->controller_type == 'front')
{
return !Context::getContext()->customer->isLogged() || self::$_cache[self::$definition['table']][$id_lang]['global'][$key];
} else {
return self::$_cache[self::$definition['table']][$id_lang]['global'][$key];
}
}
return false;
}
}
/!\ still comparing the key value every time someone tries to get a config variable, which may slow down the shop just slightly.
EDIT
Add a condition if Context is front office to fixe back office issue 'Call isLogged on NULL'

Categories