update current page number of pdf opened in new browser tab - javascript

I have a function I'm using to open PDF's in a new tab of the browser. The user may want to navigate to a different page than the one opened, so page can also be updated by the function:
openpdf: function(url, page, pageCount){
try {
console.log('the page count is ' + pageCount);
var page = new Number(page) + new Number(pageCount);
if (mobileAndTabletcheck()){
console.log('mobile detected');
return window.open(url + '#page' + page, 'somename');
}
console.log('no mobile detected')
return window.open(url + '#page=' + page, 'somename');
}
catch(e){
console.log(e)
}
},
The problem I'm having is that when the user clicks to navigate to the new page of the pdf, the URL is updated with the correct page number, but the viewer stays on the page originally opened.
Does anyone know how to make the current page update when the URL is updated?

You may use the local storage as a location to keep track of the open documents. I believe that the pdf viewer and the main page stays on the same domain. SO you may try something like this.
openpdf: function(url, page, pageCount){
try {
console.log('the page count is ' + pageCount);
var page = new Number(page) + new Number(pageCount);
if (mobileAndTabletcheck()){
console.log('mobile detected');
return window.open(url + '#page' + page, 'somename');
}
console.log('no mobile detected')
return window.open(url + '#page=' + page, 'somename');
}
catch(e){
console.log(e)
}
var openedLinks = JSON.parse(localStorage.getItem("links"));
openedLinks.push("Your URL here");
localStorage.setItem("links", JSON.stringify(names));
}
On the pdf viewer page, just update the local storage.
onpageChanged : function(){
var openedLinks = JSON.parse(localStorage.getItem("links"));
var index = items.indexOf("Your current Url");
if (index !== -1) {
openedLinks[index] = "Your updated URL";
}
localStorage.setItem("links", JSON.stringify(names));
}
And finally on the main page, use something like a timer to keep track of the opened links.
setInterval(function(){
var openedLinks = JSON.parse(localStorage.getItem("links"));
$("#someDiv").html(openedLinks.join(","));
},1000);
Hope this works for you. The code is not tested and may have errors.

Related

Want to refresh page one time on particular URL hit

I am trying to refresh the page only one time when a particular URL is hit.
The reason for this is to refresh the data on the view. My URL is
http://localhost:8072/web?#min=1&limit=80&view_type=list&model=pos.order&action=405
And solutions I have tried are
window.onload = function() {
//considering there aren't any hashes in the urls already
if(!window.location.hash) {
//setting window location
window.location = window.location + '#loaded';
//using reload() method to reload web page
window.location.reload();
}
}
(function()
{
if( window.localStorage )
{
//check if reloaded once already
if( !localStorage.getItem('firstLoad') )
{
//if not reloaded once, then set firstload to true
localStorage = true;
//reload the webpage using reload() method
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
$(document).ready(function(){
//Check if the current URL contains '# or hash'
if(document.URL.indexOf("#")==-1){
// Set the URL to whatever it was plus "#loaded".
url = document.URL+"#loaded";
location = "#loaded";
//Reload the page using reload() method
location.reload(true);
}
});
None of them worked for me. What is wrong or which direction should I choose?
Your first solution works fine, it just needed a return statement to prevent execution the rest of the code, however if your original url contains a hash, you can do the check like this:
window.onload = function() {
document.getElementById("test").textContent = window.location;
console.log(window.location.hash);
//check for our specific hash argument
if (!window.location.hash.match(/[#&]loaded(&|$)/)) {
alert("the page is about to refresh");
//setting window location
window.location = window.location + (window.location.hash ? "&" : "#") + 'loaded';
//using reload() method to reload web page
window.location.reload();
return;
}
alert("page refreshed");
}
<div id="test"></div>

how to refresh the page with original URL when URL has been changed via history.pushState()

I have used history.pushState() and now if the user refreshes the page then it is refreshing current URL which is not an original URL.
I tried detecting refresh page with a cookie, hidden filed but it is not working.
window.onload = function() {
document.cookie="PR=0";
var read_cookies = document.cookie;
var s = read_cookies;
s = s.substring(0, s.indexOf(';'));
if( s.includes("1"))
{
window.location.href = "https://www.google.com";
}
else{
document.cookie="PR=1";
}
loadURL();
};
function loadURL()
{
document.cookie="PR=1";
document.getElementById("visited").value="1";
var str="abc/b cd";
str=str.replace(/ /g, "-");
history.pushState({},"",str);
}
when user is refreshing the page I need original URL on that time.
This might be helpful. But you need control over the pushed url.
// this goes to your 'original' url
window.addEventListener('beforeunload', function (event) {
sessionStorage.setItem('lastPage', window.location.href)
}
// page with your pushed url
if (sessionStorage.getItem('lastPage') === 'PAGE_YOU_DONT_WANT_TO_BE_REACHABLE_DIRECTLY') {
window.location = 'PAGE_YOU_WANT'
}
I'm interested what the use case for this is. As far as my knowledge goes you can't suppress the refresh event completely.

jQuery opening PDF in tab - additional tabs are opening

I am using jQuery to open a PDF in a new window or tab. For the most part, it works. I can click the link, and the PDF opens in a new tab.
The problem occurs when I open another PDF.
The new PDF will open, along with the previous PDF. By the time I get to the 5th PDF, there will be 4 additional tabs from the PDFs that I previously opened.
I am working with datatables. I click a link that contains data-attributes, which then opens a modal. From inside the modal is where I'll have another click event that will then open the PDF:
$('#resultsTable').on('click', 'tr > td > a.uploadDocs', function(e)
{
e.preventDefault();
$('#editForm input, select').val(''); // <- clear previous values
var editbooking = $(this).attr('data-editbooking');
var editpartnercode = $(this).attr('data-editpartnercode');
// open PDF click event
// takes vars editbooking and editpartner to build path and filename
$('#downloadPDF').on('click', function()
{
var pdf = '../PartnerUploads/' + editpartnercode + '/' + editbooking + ".pdf";
$.get(pdf)
.done(function()
{
window.open(pdf);
}).fail(function(textStatus)
{
if(textStatus.status == 404)
{
return false;
}
});
// *** edit ***
$('#downloadPDF').off('click');
});
});
All of the above works as far as navigating to the directory, and then opening the file. But it should not open all of the files that were previously opened.
How can I find why additional tabs are being opened when opening a PDF?
As mentioned in comments, you have nested event binding.
Every time you will click on #resultsTable, you will create a new event for #downloadPDF every single time, resulting in exponentially growing the number of tabs you open.
Use $('#downloadPDF').off('click') after window.open(pdf); and one inside fail(function(textStatus).
Solution:
$('#resultsTable').on('click', 'tr > td > a.uploadDocs', function(e)
{
e.preventDefault();
$('#editForm input, select').val(''); // <- clear previous values
var editbooking = $(this).attr('data-editbooking');
var editpartnercode = $(this).attr('data-editpartnercode');
// open PDF click event
// takes vars editbooking and editpartner to build path and filename
$('#downloadPDF').on('click', function()
{
var pdf = '../PartnerUploads/' + editpartnercode + '/' + editbooking + ".pdf";
$.get(pdf)
.done(function()
{
window.open(pdf);
$('#downloadPDF').off('click');
}).fail(function(textStatus)
{
if(textStatus.status == 404)
{
return false;
}
$('#downloadPDF').off('click');
});
});
});

twitter share button quirk

Link to my in codepen: codepen.io/neel111/pen/dRBQNY?editors=1010
When the tweet button is clicked then it redirect to the page to tweet in the twitter, with a preselected text to tweet.
The JavaScript code used there is given below just for a quick look:
//-------------quotes--------
(function(){
window.addEventListener("load", makeRequest);
function makeRequest(mk){
document.getElementsByClassName("buttonQ")[0].addEventListener("click", makeRequest);
function reqListener(rl) {
if(httpR.readyState === XMLHttpRequest.DONE) {
var quote;
if(httpR.status === 200) {
quote = JSON.parse(httpR.responseText);
document.getElementsByClassName("quote")[0].innerHTML = quote[0].body;
} else {
alert("There was a problem with the request!")
}
}
}
var httpR;
httpR = new XMLHttpRequest();
httpR.onreadystatechange = reqListener
httpR.open("GET", "https://quote-api.glitch.me/pull/1", true);
httpR.send();
}
//----------------------tweet-------------------
window.addEventListener("load", function() {
document.getElementsByClassName("buttonT")[0].addEventListener("click", tweetEvent);
})
function tweetEvent(twt) {
//twt.preventDefault();
document.getElementsByClassName("quote")[0].normalize();
var tweetBody = document.getElementsByClassName("quote")[0].childNodes[0].nodeValue;
var URLBase = document.getElementsByClassName("twitter-share-button")[0].getAttribute("href");
var URLExtended = URLBase + "?hashtags=quotes&text=" + encodeURIComponent(tweetBody);
document.getElementsByClassName("twitter-share-button")[0].setAttribute("href", URLExtended);
}
})();
Quirk:
when the tweet button is clicked for the first time after the page is loaded/refreshed then the preselected text in the redirected page to tweet is
Preselected_text(quote)_from_the_main_page #tweet
But after the first click, everytime the tweet button is click the preselected text in the redirected page to tweet is
Preselected_text(quote)_from_the_main_page?hashtags=quotes #quotes
Where i am doing wrong?
So I think the problem is that you are modifying the href of the anchor tag and inserting the modified href into the dom. What I would do instead is to get rid of the in the button and build the url like you are but instead of modifying something in the dom just call window.open(extendedUrl);
Something like this should get you started:
window.addEventListener("load", function() {
document.getElementsByClassName("buttonT")[0].addEventListener("click", tweetEvent);
})
function tweetEvent(twt) {
//twt.preventDefault();
document.getElementsByClassName("quote")[0].normalize();
var tweetBody = document.getElementsByClassName("quote")[0].childNodes[0].nodeValue;
var url = "https://twitter.com/intent/tweet?hashtags=quote&text="+encodeURIComponent(tweetBody);
return window.open(url);
}
})
As you can see I have simplified the url building and then passed the resulting url to window.open which will open the url in a new window/tab (depending on user preference in their browser... find more on that here).

is it possible to make desktop alert when request for technician is issued, using jquery?

i have developed online ticketing system
i need an alert pop up message on my desktop whenever a user request for technician
heres my jquery code for adding a request
function add_rec() {
var Technician = document.getElementById("txtTech").value;
var Name = document.getElementById("txtCaller").value;
var Office = document.getElementById("txtOffice").value;
//var Request = document.getElementById("Request").value;
var Pending = document.getElementById('Pending').checked;
var Finished = document.getElementById('Finished').checked;
if (Technician == '' || Name == '' || Office == '') {
alert('Please check your entries and try again.')
} else {
if (Pending == false && Finished == false) {
alert('Please check your entries and try again.')
} else {
action("Function2.asmx/add_rec?Technician='" + Technician + "'&Name='" + Name + "'&Office='" + Office + "'&Request=''&Pending='" + Pending + "'&Finished='" + Finished + "'");
window.setTimeout(function () {
//call your display function here to update the displayed data
get_TicketStats();
get_rec();
clear_rec();
}, 100);
}
}
}
You can't make a web page (reliably) pop up a notification on the user's desktop.
Browser settings often block popups, or force them to open in new tabs, instead. There's nothing you can do about these settings.
You could use JavaScript's native alert() function. In some browsers, it forces that tab to the foreground, if the browser isn't minified.

Categories