problem in calling cgi from javascript - javascript

I am executing a cgi file directly from javascript onclick of a button. The cgi return the doc, xls, exe etc file which in turn opens SavaAs dialog to let the client save file on his machine.
Problem comes when multiple cgi files are executing in a for/while loop, It executes only the first cgi and opens the SaveAs dialog, but once the SaveAs opens it does not enter into the "for" loop again to execute another cgi which opens SaveAs dialog .
Here is the code fragment -
for(i = 0; i < dataPopup.elements['checkbox'].length; i++)
{
j=0;
obj = dataPopup.elements['checkbox'];
if(obj[i].checked)
{
var temp=obj[i].value;
temp = temp.split(".");
if(temp[1] == "txt")
{
saveWins[temp[1]] = setTimeout("document.location='../cgi/saveTextFile.cgi?fname=070319185708701_1'", 100);
}
else if(temp[1] == "pdf")
{
saveWins[temp[1]] = setTimeout("document.location='../cgi/savePdfFile.cgi?fname=065726729272220_1'", 100);
}
else if(temp[1] == "xls")
{
saveWins[temp[1]] = setTimeout("document.location = '../cgi/saveXlsFile.cgi?fname=288433243743'", 100);
}
else if((temp[1] == "doc") || (temp[1] == "docx"))
{
saveWins[temp[1]] = document.location = '../cgi/saveDocFile.cgi?fname='+temp[0];
}
saveWins[temp[1]].focus();
}
}
Please Help.

Setting document.location replaces the current document with the new document - even if it's a download. That means there is no longer a script to continue to execute.
You'll need to set the location of an iframe instead.

RoToRa means that instead of using document.location you should insert a hidden iFrame in your page and change the location of the iframe using window.frames[iframeName].location.

Related

prevent opening an html file on multiple browser tabs

I have an html file. I don't want to open that file too many times in one browser. if in the browser I already have that html file open. then when opening another tab with the same htm file, an error will appear. Is there any way to do that?. we can use javascript, html, jquery or any other way.
The only reliable way I can see to do this is to listen to a message asking "Am I here?" on a BroadcastChannel and respond with "I am here.". At page load, ask "Am I here?" and if you get the positive response, you'll know another tab already has your page.
const bc = new BroadcastChannel("Tin huynh's Broadcast Channel");
const question = "Am I here?"
const answer = "I am here."
bc.onmessage = evt => {
if (evt.data === question) {
bc.postMessage(answer)
} else if (evt.data === answer) {
alert("I am already here.")
}
}
bc.postMessage(question)
You can use JavaScript to check if the HTML file is already open in the browser before opening it in a new tab.
function openHTMLFile() {
var isFileOpen = false;
for (var i = 0; i < window.length; i++) {
if (window[i].location.href == "https://yoursite/path/to/file.html") {
isFileOpen = true;
break;
}
}
if (!isFileOpen) {
window.open("https://yoursite/path/to/file.html", "_blank");
}
}

How can i run JavaScript inside my webpage only once?

So I am trying to implement an auto language changer for my webpage.
But it keeps refreshing the page as it keeps running.
I want to run this script only once so it doesn't refresh my page forever.
I have this script:
var language = navigator.language || navigator.userLanguage;
language = language.substring( 0, 2 );
if (language == "pt" || "pt-BR" || "pt-PT"){
window.location.href = "index.html";
}
else {
window.location.href = "indexEN.html"; //
}
And its called by:
<!-- Auto Language -->
<script src="js/language.js"></script>
Think about it as if you have an infinite loop, like while (true) {} — what you need to do is break out of the loop at some point. To break out of this loop, you need to add a check to make sure you're not already on the intended page. That will stop the constant redirection.
var language = navigator.language || navigator.userLanguage
language = language.substring(0, 2)
var ptPage = 'index.html'
var enPage = 'indexEN.html'
// you're calling substring, so no need to check the variants
// your check was also incorrect :)
if (language == "pt") {
if (window.location.pathname !== '/' + ptPage) {
window.location.href = ptPage
}
} else if (window.location.pathname !== '/' + enPage) {
window.location.href = enPage
}
Refreshing the page is part of your code, as you can see here
var language = navigator.language || navigator.userLanguage;// get users default language
language = language.substring( 0, 2 );
if (language == "pt" || "pt-BR" || "pt-PT"){
window.location.href = "index.html";
}
else {
window.location.href = "indexEN.html"; //loading another html file for users who use english
}
So since you are reloading another html file, your javascript IS going to run again. A solution to this would be to make your webpage a SPA (single page application). That way you wouldn't have to reload anything (including javascript). You can also change page content and headers without actually loading a new file. SPA's are usually done in react (with react routing) but you can make then vanilla JS too.
https://medium.com/altcampus/implementing-simple-spa-routing-using-vanilla-javascript-53abe399bf3c
Don't know if it is a best practice but you can use localStorage.
if((localStorage.getItem('pageLoaded') ?? 'true') === 'true') {
alert('dsds')
localStorage.setItem('pageLoaded', 'false')
}
The alert will be executed once

Don't show page until content has fully loaded

I am creating a landing page which should exist in two languages. The texts that should be shown are in two JSON files, called accordingly "ru.json" and "en.json". When a user clicks on the "Change language" button, the following function is executed:
function changeLang(){
if (userLang == 'ru') {
userLang = 'en';
document.cookie = 'language=en';
}
else {
userLang = 'ru';
document.cookie = 'language=ru';
}
var translate = new Translate();
var attributeName = 'data-tag';
translate.init(attributeName, userLang);
translate.process();
}
Where Translate() is the following:
function Translate() {
//initialization
this.init = function(attribute, lng){
this.attribute = attribute;
if (lng !== 'en' && lng !== 'ru') {
this.lng = 'en'
}
else {
this.lng = lng;
}
};
//translate
this.process = function(){
_self = this;
var xrhFile = new XMLHttpRequest();
//load content data
xrhFile.open("GET", "./resources/js/"+this.lng+".json", false);
xrhFile.onreadystatechange = function ()
{
if(xrhFile.readyState === 4)
{
if(xrhFile.status === 200 || xrhFile.status == 0)
{
var LngObject = JSON.parse(xrhFile.responseText);
var allDom = document.getElementsByTagName("*");
for(var i =0; i < allDom.length; i++){
var elem = allDom[i];
var key = elem.getAttribute(_self.attribute);
if(key != null) {
elem.innerHTML = LngObject[key] ;
}
}
}
}
};
xrhFile.send();
}
Everything works fine, however, when a user opens the page for the first time, if his Internet connection is bad, he just sees the elements of the page without text. It is just 1-2 seconds, but still annoying.
The question is, is there any way to check the text has loaded and display the page elements only on this condition?
You can use $(document).ready() in this way
$(document).ready(function(){
//your code here;
})
You can use the JavaScript pure load event in this way
window.addEventListener('load', function () {
//your code right here;
}, false);
Source: Here
translate.process() is asynchronous code which needs to make a call to a server and wait for its response. What it means is that, when you call this function, it goes in the background to go do its own thing while the rest of the page continues loading. That is why the user sees the page while this function is still running.
One minimal way I can think around this is by adding this to your css files in the head tag.
body { display: none }
And then, under this.process function, after the for loop ends, add
document.body.style.display = 'block'
If you want to suppori IE8:
document.onreadystatechange = function () {
if (document.readyState == "interactive") {
// run some code.
}
}
Put the code you want to execute when the user initially loads the page in a DOMContentLoaded event handler like below:
document.addEventListener('DOMContentLoaded', function() {
console.log('Whereas code execution in here will be deffered until the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.');
});
console.log('This will log immediatley');
It's important to note that DOMContentLoaded is different than the load event

Can i do a scheduled task programming with javascript?

I want to do a sheduled task for every day.I have multiple servers and i want to automate the upload of html file to my other servers.In this case i have on the same folder my html and my script.js.Im currently using ajax to upload the html file but i want to do that without interference.Here is my javascript.
$(function(){
$("#drop-box").click(function(){
$("#upl").click();
});
// To prevent Browsers from opening the file when its dragged and dropped on to the page
$(document).on('drop dragover', function (e) {
e.preventDefault();
});
// Add events
$('input[type=file]').on('change', fileUpload);
// File uploader function
function fileUpload(event){
$("#drop-box").html("<p>"+event.target.value+" uploading...</p>");
files = event.target.files;
var data = new FormData();
var error = 0;
for (var i = 0; i < files.length; i++) {
var file = files[i];
console.log(file.type);
if(!file.type.match('html.*')) {
$("#drop-box").html("<p> Html only. Select another file</p>");
error = 1;
}else if(file.size > 1048576){
$("#drop-box").html("<p> Too large Payload. Select another file</p>");
error = 1;
}else{
data.append('html', file, file.name);
}
}
if(!error){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.send(data);
xhr.onload = function () {
if (xhr.status === 200) {
$("#drop-box").html("<p> File Uploaded. Select more files</p>");
} else {
$("#drop-box").html("<p> Error in upload, try again.</p>");
}
};
}
}
This script work fine with my server side, but i want to be able to perform this html upload every day.Is this possible ? what about SetInterval and SetTimeout ?
You can schedule tasks with JavaScript so that they are executed in specific intervals. But you can not upload files from the local system to the server:
JavaScript can't start file transfers on it's own due to security reasons and always needs manual user interaction to do this.
The reason why your above script works is because fileUpload() is orginally triggered by the user. As soon as you use timeout() or interval(), the browser detects that the operation was not triggered by the user and won't allow you to upload user data.

Chrome extension logic is not wοrking

I've managed to get most of my Chrome extension working, but there is a problem I can't work out.
You can grab it here if you want and load it as an unpacked extension.
After loading it works like this.
You are prompted that they need to enter a URL on the options page.
You enter a URL (e.g. http://example.com) on the options page as asked and click save, and then when you click the icon in the toolbar you can see the web page appear in the popup.
If you then go and removes the URL from the options page and clicks save, then the popup does not show the original prompt page they saw at the beginning.
I think this code (from popup.js) is at fault, but I can't see why it won't work.
var url = localStorage.url;
var alturl = chrome.extension.getURL("need-to-enter-url.html");
var element = document.getElementById("testerURL");
if (url != undefined || url != null) {
element.src = url;
} else {
element.src = alturl;
};
When you "remove" the url you are actually saving an empty string. localStorage.url = "" so your value checking is failing. I would also recommend tweaking the if logic to be clearer.
Use something like this:
if (url === undefined || url === null || url === "") {
element.src = alturl;
} else {
element.src = url;
}
Optionally you can rely on JavaScript's truthiness.
if (url) {
element.src = url;
} else {
element.src = alturl;
}

Categories

Resources