Displaying file name extensions in html using external js - javascript

I am trying to display the file name extensions using html and an external javascript but my website remains blank. I got this example code from another stackoverflow answer but I am unable to get it to work. Shouldn't the extension of my variables be shown when I call the function in my html like such?
<script>getExtension(file1);</script>
js
var file1 = "index.php";
var file2 = "test.js";
function getExtension(filename) {
return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename;
}

You are getting the extension correctly but you don't write it to your output anywhere. There are different approaches to output the value, here are two possibilities:
document.write()
The Document.write() method writes a string of text to a document stream. But be careful, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
var file1 = "index.php";
var file2 = "test.js";
function getExtension(filename) {
return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename;
}
// This will add "php" to the document
document.write(getExtension(file1));
// This will clear the document and replace it with "js" - added 1 second delay to visualize it
window.onload = function () {
setTimeout( 'document.write(getExtension(file2))', 1000 );
}
<h1>My content</h1>
createTextNode() + appendChild()
You can also create a text node and append it to your body. Of course you could also create any other element and add it wherever you want.
var file1 = "index.php";
var file2 = "test.js";
function getExtension(filename) {
return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename;
}
// Create a text node
var t = document.createTextNode(getExtension(file1));
// Append it to the body
document.body.appendChild(t);
<h1>My content</h1>

Related

new html file to be created in the same folder in which HTML is present

i want the new html file to be created in the same folder in which HTML is present. please help me. am searching a lot , no luck
<script>
function makeDocument() {
var doc = document.implementation.createHTMLDocument("newdoc");
var p = doc.createElement("p");
p.innerHTML = "This is a new paragraph.";
try {
doc.body.appendChild(p);
} catch(e) {
console.log(e);
}
var opened = window.open("");
opened.document.write(doc);
}
</script>
Use a back-end server. Because the HTML page and the scripts are executed on the client-side. You can't really create a file on the client-side while the page is loaded in a browser.
The other way around, you won't want the client to create arbitrary files on the server as well. It poses a great security risk and might lead to possible remote code execution (RCE).
You do not have a closing brace on your function
<script>
function makeDocument() {
var doc = document.implementation.createHTMLDocument("newdoc");
var p = doc.createElement("p");
p.innerHTML = "This is a new paragraph.";
try {
doc.body.appendChild(p);
} catch(e) {
console.log(e);
}
var opened = window.open("");
opened.document.write(doc);
}
</script>
As for the wording of your question, if you are asking to create a new file that gets saved, then Aviv Lo's answer is what you need

Returned JavaScript value wont render inside a div element

This a basic question (Posting this again, as it was not re-opened after I updated the question). But I couldn't find any duplicates on SO.
This is a script I intend to use in my project on different pages. The purpose is to override the default ID shown in a span element to the order number from the URL parameter session_order. This doesn't affect anything and only enhances the UX for my project.
scripts.js (loaded in the header):
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
And in my HTML template, I call the function this way,
<div onload="this.innerHTML = get_url_parameter(window.location.href, 'session_order');">24</div>
Also tried this,
<div><script type="text/javascript">document.write(get_url_parameter(window.location.href, 'session_order'));</script></div>
When the page is rendered, nothing changes. No errors or warnings in the console either for the first case.
For the second case, console logged an error Uncaught ReferenceError: get_url_parameter is not defined, although script.js loads before the div element (without any errors).
Normally, I'd do this on the server-side with Flask, but I am trying out JavaScript (I am new to JavaScript) as it's merely a UX enhancement.
What am I missing?
Try this:
// This is commented because it can't be tested inside the stackoverflow editor
//const url = window.location.href;
const url = 'https://example.com?session_order=13';
function get_url_parameter(url, parameter) {
const u = new URL(url);
return u.searchParams.get(parameter);
}
window.onload = function() {
const el = document.getElementById('sessionOrder');
const val = get_url_parameter(url, 'session_order');
if (val) {
el.innerHTML = val;
}
}
<span id="sessionOrder">24</span>
Define the function you need for getting the URL param and then on the window load event, get the URL parameter and update the element.
Here you go. Try to stay away from inline scripts using document.write.
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
window.addEventListener('load', function() {
const url = 'https://yourpagesdomain.name/?session_order=hello'; //window.location.href;
const sessionOrder = get_url_parameter(url, 'session_order');
document.getElementById('sessionOrder').innerText = sessionOrder;
});
<div id="sessionOrder"></div>
The order of your markup and script matters...
<div></div>
<script>
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
</script>
<script>
document.querySelector('div').innerHTML = get_url_parameter('https://example.com?session_order=2', 'session_order');
</script>

javascript pass media EventListener to html (html5) media.currentTime

*update here is my code edit as you see working) https://codeshare.io/a3ZJ9g
i need to pass on a javascript varible to a html link...
my original question was here HTML5 video get currentTime not working with media events javscript addEventListener
working code:
<script>
var media = document.getElementById('myVideo');
// durationchange
var isdurationchange = function(e) {
$("#output").html(media.currentTime);
var x = document.createElement("a");
};
media.addEventListener("timeupdate", isdurationchange, true)
</script>
that code works
but i need it to echo the currentTime value to the html page such as
document.write("<a href=/time.htm?currentTime='.media.addEventListener("timeupdate", isdurationchange, true).'>link</a>;);
so it would print out
<a href=time.htm?currentTime=currenttimefromjavascript>link</a>
thank you
i did read:
how to pass javascript variable to html tag
How can I pass value from javascript to html?
someone suggested:
// insert the `a` somewhere appropriate so it can be clicked on:
const a = document.body.appendChild(document.createElement("a"));
a.textContent = 'Link to current time';
const isdurationchange = function(e) {
a.href = `\\time.htm?currentTime=${media.currentTime}`;
};
but where does that go?
document.write tries to write to the current document. If the document has already been processed, the document will be replaced with a blank one with your argument. You don't want that; use the proper DOM methods instead.
If, for an element you create dynamically, you want to change its href on every timeupdate, you would do:
// insert the `a` somewhere appropriate so it can be clicked on:
const a = document.body.appendChild(document.createElement("a"));
a.textContent = 'Link to current time';
const isdurationchange = function(e) {
a.href = `\\time.htm?currentTime=${media.currentTime}`;
};

HTML JavaScript delay downloading img src until node in DOM

Hi I have markup sent to me from a server and I set it as the innerHTML of a div element for the purpose of traversing the tree, finding image nodes, and changing their src values. Is there a way to prevent the original src value from being downloaded?
Here is what I am doing
function replaceImageSrcsInMarkup(markup) {
var div = document.createElement('div');
div.innerHTML = markup;
var images = div.getElementsByTagName('img');
images.forEach(replaceSrc);
return div.innerHTML;
}
The problem is that in browsers as soon as you do:
var img = document.createElement('img'); img.src = 'someurl.com' the browser fires off a request to someurl.com. Is there a way to prevent this without resorting to parsing the markup myself? If there is in no other way does anyone know a good way of parsing the markup with as little code as possible to accomplish my goal?
I know you are already happy with your solution, but I think it would be worth sharing a safe method for future users.
You can now simply use the DOMParser object to generate an external document from your HTML string, instead of using a div created by your current document as container.
DOMParser specifically avoids the pitfalls mentioned in the question and other threats: no img src download, no JavaScript execution, even in elements attributes.
So in your case you can safely do:
function replaceImageSrcsInMarkup(markup) {
var parser = new DOMParser(),
doc = parser.parseFromString(markup, "text/html");
// Manipulate `doc` as a regular document
var images = doc.getElementsByTagName('img');
for (var i = 0; i < images.length; i += 1) {
replaceSrc(images[i]);
}
return doc.body.innerHTML;
}
Demo: http://jsfiddle.net/94b7gyg9/1/
Note: with your current code, browsers will still try downloading the resource initially specified in your img nodes src attribute, even if you change it before the end of JS execution. Trace network transactions in this demo: http://jsfiddle.net/94b7gyg9/
Rather than append the new markup to the DOM before you change the img sources, create an element, set it's inner HTML, change the source of the images and then finally, append the changed markup to the page.
Here's a fully-worked sample.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
//function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
//function newTxt(txt){return document.createTextNode(txt);}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('goBtn').addEventListener('click', onGoBtnClick, false);
}
var dummyString = "<img src='img/girl.png'/><img src='img/gfx07.jpg'/>";
function onGoBtnClick(evt)
{
var div = newEl('div');
div.innerHTML = dummyString;
var mImgs = allByTag('img', div);
for (var i=0, n=mImgs.length; i<n; i++)
{
mImgs[i].src = "img/murderface.jpg";
}
document.body.appendChild(div);
}
</script>
<style>
</style>
</head>
<body>
<button id='goBtn'>GO!</button>
</body>
</html>
You could directly parse the markup string using a regex to replace the img src. Searching for all the img src urls in the string and then replacing them with the new url.
var regex = /<img[^>]+src="?([^"\s]+)"?\s*\/>/g;
var imgUrls = [];
while ( m = regex.exec( markup ) ) {
imgUrls.push( m[1] );
}
imgUrls.forEach(function(url) {
markup = markup.replace(url,'new-url');
});
Another solution might be, if you have access to it, to set the all the img src to an empty string, and put the url in in a data-src attribute. Having your markup string look like something like this
markup = '
';
Then setting this markup to your div.innerHTML won't trigger any download from the browser. And you can still parse it using regular DOM selector.
div.innerHTML = markup;
var images = div.getElementsByTagName('img');
images.forEach(function(img){
var oldSrc = img.getAttribute('data-src');
img.setAttribute('src', 'new-url');
});

javascript get current filescript path

How can I get the path of the current script in javascript using jQuery
for example I have site.com/js/script.js and there is a code in this script:
$(document).ready(function() {
alert( ... this code ... );
}
It Should return alert box with the "/js/script.js" message. This function should work like magic __FILE__ constant in php
So, why do I need this?
I want to set background image dynamically:
$("somediv").css("background-image", "url(" + $SCRIPT_PATH + "/images/img.png)");
and images directory is the /js directory, near the script.js file
and js folder's name can be dynamically set, so script and images can be in the /myprogect/javascript-files directory
You can rely on the fact that each <script> element has to be evaluated* before the next one is inserted into the DOM.
This means that the script currently evaluated (as long as it is part of your markup and not dynamically inserted) will be the last one in the NodeList retrieved with getElementsByTagName( 'script' ).
This allows you to read that elements src attribute and from that determine the folder that the script is being served from - like this:
var scriptEls = document.getElementsByTagName( 'script' );
var thisScriptEl = scriptEls[scriptEls.length - 1];
var scriptPath = thisScriptEl.src;
var scriptFolder = scriptPath.substr(0, scriptPath.lastIndexOf( '/' )+1 );
console.log( [scriptPath, scriptFolder] );
I tried this technique with 3 scripts loaded from different folders and get this output
/*
["http://127.0.0.1:8000/dfhdfh/folder1/script1.js", "http://127.0.0.1:8000/dfhdfh/folder1/"]
["http://127.0.0.1:8000/dfhdfh/folder2/script2.js", "http://127.0.0.1:8000/dfhdfh/folder2/"]
["http://127.0.0.1:8000/dfhdfh/folder3/script3.js", "http://127.0.0.1:8000/dfhdfh/folder3/"]
*/
* from John Resigs blog linked to above
This means that when the script finally executes that it'll be the
last script in the DOM - and even the last element in the DOM (the
rest of the DOM is built incrementally as it hits more script tags, or
until the end of the document).
Update
As pimvdb points out - this will work as the script is being evaluated. You will need to store the path somehow if you are going to use it later. You can't query the DOM at a later point. If you use the same snippet for each script the value of scriptFolder will be overwritten for each script. You should give each script a unique variable perhaps?
Wrapping your script in its own scope closes over the value of scriptFolder making it available to the rest of the script without fear of being overwritten
(function() {
var scriptEls = document.getElementsByTagName( 'script' );
var thisScriptEl = scriptEls[scriptEls.length - 1];
var scriptPath = thisScriptEl.src;
var scriptFolder = scriptPath.substr(0, scriptPath.lastIndexOf( '/' )+1 );
$( function(){
$('#my-div').click(function(e){
alert(scriptFolder);
});
});
})();
Add the following code to your JS :
var retrieveURL = function(filename) {
var scripts = document.getElementsByTagName('script');
if (scripts && scripts.length > 0) {
for (var i in scripts) {
if (scripts[i].src && scripts[i].src.match(new RegExp(filename+'\\.js$'))) {
return scripts[i].src.replace(new RegExp('(.*)'+filename+'\\.js$'), '$1');
}
}
}
};
Suppose these are the scripts called in your HTML :
<script src="assets/js/awesome.js"></script>
<script src="assets/js/oldcode/fancy-stuff.js"></script>
<script src="assets/js/jquery/cool-plugin.js"></script>
Then, you can use the function like this
var awesomeURL = retrieveURL('awesome');
// result : 'assets/js/'
var awesomeURL = retrieveURL('fancy-stuff');
// result : 'assets/js/oldcode/'
var awesomeURL = retrieveURL('cool-plugin');
// result : 'assets/js/jquery/'
Note that this only works when there are no two script files in your HTML with the same name. If you have two scripts with the same name that are located in a different folder, the result will be unreliable.
Note
If you dynamically add scripts to your page, you need to make sure your code is executed after the last script has been added to the DOM.
The follow example shows how to do this with one dynamically loaded script. It outputs a JSON array with the src link for scripts that load an external js file and a base64-encoded string of the JS content for inline scripts:
var addScript = function(src, callback) {
var s = document.createElement( 'script' );
s.setAttribute( 'src', src );
document.body.appendChild( s );
s.onload = callback;
}
var retrieveURL = function(filename) {
var scripts = document.getElementsByTagName('script');
if (scripts && scripts.length > 0) {
for (var i in scripts) {
if (scripts[i].src && scripts[i].src.match(new RegExp(filename+'\\.js$'))) {
return scripts[i].src.replace(new RegExp('(.*)'+filename+'\\.js$'), '$1');
}
}
}
};
addScript('https://code.jquery.com/jquery-1.12.4.min.js', function() {
var scripts = document.getElementsByTagName('script');
var sources = [];
for (var i = 0; i < scripts.length; i++) {
if(scripts[i].src == '') {
sources.push(btoa(scripts[i].innerHTML));
} else {
sources.push(scripts[i].src);
}
}
document.body.innerHTML += '<pre>' + JSON.stringify(sources,null,2) + '</pre>';
});
See also this Fiddle.
I don't think jQuery provide such a functionality.
Anyway you can get currentc script path path (both fully http and relative) by reading the answer here: What is my script src URL?
Can't you set a kind of path variable in the js? So, you save the path of the file in the file itself.
For example:
$(function() {
var FilePath = "js/some/path";
setMyDynamicImageUsingPath(FilePath);
});
// ...
function setMyDynamicImageUsingPath(path) {
$("somediv").css("background-image", "url(" + path + "/images/img.png)");
}

Categories

Resources