Get JS src params inside of JS file - javascript

I've got a JS file called test.js, I'd like to pull in and utilize params that are attached to the extension of this file, but for some reason when I console log the results, I'm not seeing them.
How can I use the URL of a JS file to bring in variables, e.g:
<script src="test.js?var1=value1&var2=value2"></script>
The contents of my JS file is:
const search = window.location.search
console.log(search) <-- not seeing var1 or var2
What am I missing?
P.S: I cannot define a variable outside of the JS file and then use it within, surely there's a way to use the attached vars on the URL?

window.location is the location of the HTML document the script is running inside.
To get the value of the src attribute you need to use document.currentScript to get the element, then you can read its src property (and then you can parse it with URL()).
Unless you are sending the values to the server hosting the JS for server side processing, you'd likely be better off using data attributes instead.
<script data-foo="example">
console.log(document.currentScript.dataset.foo);
</script>

window.location.search returns the query string part of the URL[the current location of the document]. If you want to access the src of the script element, you may assign any unique identifier to the tag and may access the src property.
To access search parameters, you may use new URL(src)
let src = document.getElementById('src').src;
console.log('src - ', src);
const url = new URL(src);
console.log('search params - ', url.search);
<script src="test.js?var1=value1&var2=value2" id="src"></script>

Related

How to add img elements with Javascript when using Django?

I am trying to dynamically insert img elements to the website I am building which uses Django for the back-end. The images change often so I pass the src from Python to Javascript like this:
views.py
path='{% static "../static/assets/'+image_name+'" %}'
response = render(request, 'main.html',{'image_path':path})
return response
Then I declare a global variable in the template so I can use this in the .js files.
main.html
var imagePath = {{image_path|safe}}
Then I use Javascript to pass this as src to new img elements. However, when I do it, Django cannot find images. When I put the string as src to a img element manually, it works.
Does anyone know how to solve this?
You need to use this:
from django.templatetags.static import static
path = static(f'assets/{image_name}')
response = render(request, 'main.html',{'image_path':path})
return response

How to use Javascript to get current file name and use as a variable in Pug/HTML template?

I would like to pass the file name to the tag in an html document. I would therefor like to grab it and put it in a variable. I am using Pug, so can use javascript before compiling to html.
This is obviously, obviously not correct code, but is the idea of what I need:
let title tag === filename.pug
I have tried this and it works in the browser, but it works off the url and I would like to do it off the OSX file path.
var filename = (location.pathname.substring(location.pathname.lastIndexOf("/") + 1)).replace('.html','');
document.getElementById("title").innerHTML = filename;

how to get the absolute path of an excuting js in the js?

for instance, the page of HTML contains the js, and the js's src is /js/test.js, and in this js file, can I get the string of /js/test.js while the js is excuted?
__dirname and process.cwd() can both do it in Node.js, but not work in js of broswer
can anyone help me?
HTML
<script src="/some/path.js" id="script1"></script>
<script src="/some/path2.js" id="script2"></script>
JS
// /some/path.js
var path = document.querySelector('#script1').getAttribute('src');
// /some/path2.js
var path = document.querySelector('#script2').getAttribute('src');
In a browser, a script is loaded through HTTP request. The URI (the bits after the host name) does not necessarily correspond to the file name.
If you just want the src attribute, then you can refer to this answer, which recommends using document.currentScript to obtain the script element.
const path = document.currentScript.getAttribute('src');

Javascript File from Local Storage

I have a large JavaScript file that I'd rather not send to the client on each request and it's too large for the browser to cache.
My thought is that I will save the file to HTML5 local storage and attempt to retrieve it. If the file is found then I'd like to link/import/export(I don't know the proper terminology) it into the same scope that a html src tag would.
My question is: how do I take a file that I've pulled from local storage and get my webpage to recognize it as a JavaScript file that was included via src tag? (minus the logic for pulling the file from storage)
My question is: how do I take a file that I've pulled from local storage and get my webpage to recognize it as a JavaScript file that was included via src tag?
Two possible ways (amongst maybe others):
create a script element, and assign your JS code as the “text content” of that element before appending it to the DOM. “Text content” in quotes here, because it is not as simple as it sounds cross-browser – see f.e. Javascript script element set inner text, Executing elements inserted with .innerHTML, or
assign your script code to the src attribute of a script element via a Data URI, data:text/javascript,… – but that approach has several disadvantages as well, also mostly in older IE (size limitation; only “non-navigable” content, meaning no scripts). But depending on your target environment that might well work. You will not necessarily need to base64 encode the script code, URL-percent-encoding via encodeURIComponent should work as well.
Take a look at this:
http://jsfiddle.net/611e96mz/1/
var tag = getId('testjs'),
a = getId('a'),
b = getId('b'),
c = getId('c'),
script;
a.addEventListener('click', function () {
localStorage.setItem('js', tag.innerHTML);
});
b.addEventListener('click', function () {
script.textContent = localStorage.getItem('js');
});
c.addEventListener('click', function () {
document.body.appendChild(script);
alertMe();
});
var script = document.createElement("script");
script.type = "text/javascript";
function getId(x) {
return document.getElementById(x);
}
You can use JSON to stringfy your file content and put it on localstorage.
var content = JSON.stringify([1, "some info"]); // '[1,"some info"]'
localStorage.setItem('fileContent', content);
// Retrieve
var content = localStorage.getItem('fileContent');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

How would I find a html files parent directory name?

I need to know a html files parent directory so I can access a file in it named the same as the directory. I just need the directory name as a string.
You can try something like
window.location.pathname
But again depends on what you are trying to achieve, show some code.
Background
As #NewUser says, use window.location.pathname if you want only the path. Example: on this page, that gives:
/questions/25717173/how-would-i-find-a-html-files-parent-directory-name
You indicated that you are dealing with an HTML file, though, which implies a file name and file ending (.htm, .html, etc.). So, to get the full URL, minus the file name, you can try using .replace(/[^\/]+$/, ''), like this:
var url = 'http://www.example.com/foo/bar/baz.htm';
alert(url.replace(/[^\/]+$/, ''));
// gives http://www.example.com/foo/bar/
Putting It All Together
To do it without hard-coding the URL:
var path = window.location.toString().replace(/[^\/]+$/, '');
alert(path);

Categories