I'm trying to create a script that will make it easier for users to use a custom button and I have something like
<script src="http://host.com/file.js?id=12345"></script>
What I wonder is how can I, in the file.js get that id parameter.
if I use document, it will get the original html page that has the script line and what I need is that id.
is there any way i can get that id successfully? What should be the scope?
added
the idea is that I can have several buttons in the page for example to have a small and simply list:
<ul>
<li><script src="http://host.com/file.js?id=12345"></script></li>
<li><script src="http://host.com/file.js?id=23456"></script></li>
<li><script src="http://host.com/file.js?id=34567"></script></li>
</ul>
this will ultimately translate to
<ul>
<li><a class="view40btn" href="#" data-id="12345"><strong>V40</strong> Watch the video</a></li>
<li><a class="view40btn" href="#" data-id="23456"><strong>V40</strong> Watch the video</a></li>
<li><a class="view40btn" href="#" data-id="34567"><strong>V40</strong> Watch the video</a></li>
</ul>
the list above will look like this in HTML:
My only issue is that I can't assign the correct id to the data-id attribute as this is generated in the file.js.
result
from Paulpro answer I got it working with his idea and knowing that the client will have much more scripts loaded and several with id's I changed it a bit for the final and working version:
var id = (function(){
var scripts = document.getElementsByTagName('script');
for(var i = 0, result = {}; i < scripts.length; i++)
if(scripts[i].hasAttribute('data-viewfileid'))
result['id'] = decodeURIComponent(scripts[i].getAttribute('data-viewfileid'));
return result['id'];
})();
var html = '<a class="view40btn" href="#" data-id="' + id + '"><strong>V40</strong> Watch the video</a>';
document.write(html);
the script for the user would only be:
<script data-viewfileid="4444" src="file.js" type="text/javascript"></script>
You can get the last script element on the page (which will always be the currently executing one):
var scripts = document.getElementsByTagName('script');
var s = scripts[scripts.length - 1];
Then modify one of the query string parsers from this question to work with that scripts src property:
var url = s.src;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][2]);
}
That will give you an object containing all the query string properties on the current script. You can just access the properties like:
result['id']; // '12345'
In summary
To get the id parameter from within file.js, add the following code to the top of file.js:
var id = (function(){
var scripts = document.getElementsByTagName('script');
var s = scripts[scripts.length - 1];
var qs = s.src.substring(s.src.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][3]);
}
return result['id'];
})();
Make sure it is not in any callback functions like a DOMReady callback.
Edit: You can probably reduce your script to:
var scripts = document.getElementsByTagName('script');
var id = scripts[scripts.length - 1].getAttribute('data-viewfileid');
var html = '<a class="view40btn" href="#" data-id="' + id + '"><strong>V40</strong> Watch the video</a>';
document.write(html);
JavaScript doesn't know anything about the script tag that loaded it. However, there are a few workarounds.
If the file is being preprocessed on the server, you could make the server render the value in the response:
(function() {
var id = <%= params.id %>;
//other stuff here
}());
Or you could give the script tag an id, and make your code find it and pull out the URL.
HTML:
<script src="http://host.com/file.js?id=12345" id="myscript"></script>
JS:
var id = document.getElementById('myscript').split('id=')[1];
Or in modern browsers you could perhaps do something like this to find script tags that match where you know the script is.
var scriptTag = document.querySelector('script[src^="http://host.com/file.js"]');
var id = scriptTag.src.split('id=')[1];
One more solution is to parse .js files with php interpreter. For example in apache configuration:
AddType application/x-httpd-php .js
And in JS:
alert('<?=$_GET["id"]?>');
You can put an ID on anything, including a script tag. So you can do something like this:
HTML:
<script id="myScript" src="http://host.com/file.js?id=12345"></script>
JS:
document.getElementById('myScript').src.split('=')[1]; to get the ID from that particular example string.
If that query string represents a timestamp (in which case you need the latest version) you can modify the JavaScript code to fetch the latest <script> tag like so:
var scripts = document.getElementsByTag('script');
var latestScriptId = scripts[scripts.length-1].src.split('=')[1];
EDIT: In the context of your new edit, you would then take latestScriptId and assign it to the data.id attribute corresponding to the button you would like to create...though again, semantically, it would just make more sense to use HTML's given id attribute, and additionally, since you are not using the href property for the anchor <a> tag, you're better off using a <button> element. So something like this would suffice:
var myButton = document.createElement('button');
myButton.className += 'view40btn';
myButton.id = latestScriptId;
According to your clarifications, what you asking how to do is not what you want to do.
Instead, include one script, and have multiple placeholder nodes.
HTML:
<ul>
<li class="mybutton" data-id="12345"></li>
<li class="mybutton" data-id="23456"></li>
<li class="mybutton" data-id="34567"></li>
</ul>
<script src="myscript.js"></script>
JS:
// myscript.js
var buttons = document.getElementsByClassName('mybutton');
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
button.innerHTML = "my button html template here with id: "+ button.dataset.id;
}
See it work here: http://jsfiddle.net/zAdnB/
Javascript code does not "realise", that it is a part of some file. JS file is not "executable", there is no main method, which should be run after loading the file. You can not pass GET parameters to it - it is not clear how they should be interpreted.
In your HTML page, you should listen to "onload" method and then call the function from your file with your parameter.
Related
How can I pick up image name in html using JavaScript? I searched google and there are some documents about how to get image name on <img> tag,
var filename = tag.replace( /^.*?([^\/]+)\..+?$/, '$1' );
But it return just one name of images. What I'm going to do is get all images name. Imagine the html below,
<html>
<body>
<div class="imagebox">
<img src="/some/path/imageOne.jpg">
<img src="/some/path/imageTwo.jpg">
<img src="/some/path/imageThree.jpg">
</div>
</body>
</html>
after magic, return
imageOne, imageTwo, imageThree. How can I do this..?
Add the following Javascript code at the bottom of your html page :
Solution for browser environment :
var images = document.getElementsByTagName('img');
var images_urls = [];
var images_names = [];
var tmp;
for(var i=0;i < images.length;i++){
images_urls[i] = images[i].getAttribute('src');
tmp = images[i].getAttribute('src').split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
and now images_names is an array containing the image names, in this case imageOne,imageTwo and imageThree
Solution for Node.js environment:
lets say you have images url stored in images variable like this :
var images = ["/some/path/imageOne.jpg", "/some/path/imageTwo.jpg", "/some/path/imageThree.jpg"];
you can use Regex, but in this case you can do it easily without using Regex, just split each image url and grab the last part of it, pretty simple, something like this :
var images_names = [];
var tmp
for(var i=0;i < images.length;i++){
tmp = images[i].split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
It is the same solution for both Browser and Node.js environment except for the way you get the elements.
Hope this helps.
I am trying to hash data using JavaScript. When I run the first code it will hash using document.write. Now I try the second code to hash by content id it didn't work. Can anyone explain why?
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha256.js"></script>
<script>
var hash = CryptoJS.SHA256("hello");
document.write(hash.toString(CryptoJS.enc.Hex));
</script>
using this first method will work very fine
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
<script>
var hash = CryptoJS.SHA256;
var it = (hash.toString(CryptoJS.enc.Hex));
document.getElementById('hashit').innerHTML = 'it';
</script>
<p id="hashit">Hello</p>
If you want to hash something in-place in an element then you need to read out the value/text, hash it and write the text back:
var element = document.getElementById('hashit');
var hash = CryptoJS.SHA256(element.innerHTML);
element.innerHTML = hash.toString();
Here is a runnable snippet which changes the value after 2 seconds.
setTimeout(function(){
var element = document.getElementById('hashit');
var hash = CryptoJS.SHA256(element.innerHTML);
element.innerHTML = hash.toString();
}, 2000);
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/sha256.js"></script>
<p id="hashit">Hello</p>
Keep in mind that JavaScript is not like PHP. You can't simply use variables in strings like this element.innerHTML = 'it';. You have to useelement.innerHTML = it;.
I have a list in one file html called "filed1":
<ul>
<li>Nombre:<a class="boton" onclick=move() title="Caja">Caja</a><br>
<FONT SIZE=2>Fecha: 21/12/1994</font></font></li>
</ul>
Now I want to change a string in other html "filed2":
<a id="logo-header2">
<h1>
<span class="site-name" id="element">Details</span><br>
</h1>
</a>
Using Java Script:
function move() {
mywindow = window.open("file2.html");
mywindow.document.getElementById("element").innerHTML="Changed");
}
But there is an error which says that mywindow.document.getElementById("element") is NULL, why? The id element exists in the other window. Is there another way to change the string?
The problem is that you are trying to retrieve the DOM element before the window is loaded.
Try following
mywindow.onload = function() {
mywindow.document.getElementById("element").innerHTML="Changed";
}
Like #nikhil mentioned, mywindow is undefined when you're calling it, and you'll need to place your code into something triggered by the onload event.
Another approach you can try is perhaps passing the string as a variable in the url, like so:
function move(){
window.open("file2.html?str=Changed");
}
And then in file2.html, try something that runs on page load:
window.onload = function(){
var str = $_GET('str');
document.getElementById("element").innerHTML = str;
};
function $_GET(q){
var $_GET = {};
if(document.location.toString().indexOf('?') !== -1){
var query = document.location
.toString()
.replace(/^.*?\?/, '')//Get the query string
.replace(/#.*$/, '')//and remove any existing hash string
.split('&');
for(var i=0, l=query.length; i<l; i++){
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
return $_GET[q];
}
The $_GET function I included is just for getting query string parameters, and function much like $_GET[] in php.
I have a page with a download button like this:
<a href="http://www.example.nl/filename.pdf" download>DOWNLOAD</a>
Below, I want (text) to automatically display "filename.pdf" (rather than having to do this by hand hundreds of times).
I found the script below that displays the filename of the PAGE but I want it to display the FILENAME of a HREF I've used on the actual page.
Any help is much appreciated.
<script type="text/javascript">
var segment_str = window.location.pathname;
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.write(last_segment);
</script>
Thanks in advance!
Not sure where you want the "text" to display... so I put it in a div
<a href="http://www.example.nl/filename.pdf" download>DOWNLOAD</a>
<div id="result">
</div>
The big change, is to get all the "a" tags, using getElementsByTagName... and then iterating over the list, and then you can use the string split, and pop off the last segment before appending it to a destination.
var input = document.getElementsByTagName('a');
for(i = 0;i < input.length; i++)
{
var segment_str = input[i].href;
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.getElementById("result").innerText += last_segment;
}
Maybe this will help.
<div id=download1></div>
<script>
var filename = 'example.pdf';
$('#download1').html('' + filename + '');
</script>
I would like to change the id of a tag from within the external script it points to. What is the proper way of doing this?
Here is my script tag:
<script id="ID1" type="text/javascript" src="PATH_TO_EXTERNAL_JS"></script>
And here is what I'm trying to do from within my external script:
var sessionID = generateSessionID();
var scripts = document.getElementsByTagName('script');
var script = scripts[scripts.length - 1];
script.id = script.id + "_" + sessionID;
However, when I look at the live DOM tree in firebug, i see 2 scripts referenced in the DOM. One with the original ID, and one with the new ID.
Thanks!
Use setAttribute
script.setAttribute("id", script.id + "_" + sessionID);
I think You should modify Your code, to somewhat like this:
var i = 0
var sessionID = generateSessionID();
var scripts = document.getElementsByTagName('script');
var script = null;
for (i = 0; i < scripts.length; i++)
if (scripts[i].src.toString() == 'PATH_TO_EXTERNAL_JS'){
script = scripts[i];
break;
}
if (script)
script.id = script.id + "_" + sessionID;
In other words. Get all the SCRIPT elements, iterate through this collection to look for an element that has some known attribute (src in this example) and if it's found, set it's new id.
You need to remove the old script, if your going to do it that way. Although Mike Lewis answer has a better method.
document.removeChild(originalScript)