I'm having an issue with the following script.
The calling script is:
script src="//192.168.6.10/js/cYJIeCa30E.js
the resulting script needs to be parsed for cYJIeCa30E.js
in this script I have:
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
var name = scriptName.split('/');
alert(name);
alert(name) gives comma separated values:
http:,,192.168.6.10,js,cYJIeCa30E.js
but
alert(name[4]) gives ':' not the value after the last '/'
any idea what I am missing?
Thanks
The proper way will be like so:
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
var a = scriptName.split('/');
alert(a[4]); //cYJIeCa30E.js
Note You can change the variable a to any other variable. Thanks to Mike C for the MDN link
Related
I'm new to Script and was wondering if I could get help with a question. I'm currently trying to auto-fill a Google Doc from a Google Form submission. I've had success with a small test in the past, but since trying it a second time with a bit of a larger form, I'm encountering this error:
"Exception: The parameters (String,DriveApp.File) don't match the method signature for DriveApp.File.makeCopy"
It isn't immediately clear to me what this is telling me. What I do know is that I'm not doing anything differently than my last small scale test so the script I'm running looks on the surface to be solid, so I'm hoping someone could help me out with pointing out what's wrong. Here's the script:
function autoFillFormFromDoc(e) {
var clientCode = e.values[1];
var email = e.values[2];
var warningSigns = e.values[3];
var internalCopingStrategies = e.values[4];
var peopleAndSocial = e.values[5];
var peopleWhoCare = e.values[6];
var creatingSafety = e.values[7];
var clientName = e.values[8];
var date = e.values[9];
var templateFile = DriveApp.getFileById("1Vs8y3eZbyBlef8HlV7v9nhSRvaH39Cg5P0Q5zhpZBA");
var templateResponseFolder = DriveApp.getFileById("1OxsOwU6rAvohqRqDVOfH_f70kvu30HZp");
var copy = templateFile.makeCopy(clientName, templateResponseFolder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText("{{ClientCode}}", clientCode);
body.replaceText("{{Email}}", email);
body.replaceText("{{WarningSigns}}", warningSigns);
body.replaceText("{{InternalCopingStrategies}}", internalCopingStrategies);
body.replaceText("{{PeopleAndSocial}}", peopleAndSocial);
body.replaceText("{{PeopleWhoCare}}", peopleWhoCare);
body.replaceText("{{CreatingSafety}}", creatingSafety);
body.replaceText("{{ClientName}}", clientName);
body.replaceText("{{Date}}", date);
doc.saveAndClose();
}
Issue:
File.makeCopy(name, destination) expects two arguments
name of type string and
destination of type folder
The script calls destination with type file. Therefore it errors out with
The parameters (String,DriveApp.File) don't match the method signature for DriveApp.File.makeCopy
Solution:
Get folder instead of file:
var templateResponseFolder = DriveApp.getFolderById("[FOLDER_ID]");
I have this script code:
<script src="http://example.com/embed.js?q=123¶meter1=450¶meter2=300"></script>
How can i get the values of q(123)and parameter1(450) and parameter2(300) and use them into embed.js file? I want to make conditions into my embed.js by using these values. How can i achieve that?
Give the script element and ID attribute like this:
<script id="embed-script" src="http://example.com/embed.js?q=123¶meter1=450¶meter2=300"></script>
Javascript:
var url = document.getElementById('embed-script');
function parseGet(val) {
var result = "",
tmp = [];
var items = url.src.split("?")[1].split('&');
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === val)
result = decodeURIComponent(tmp[1]);
}
return result;
}
Get the values like this, in embed.js:
var value1 = parseGet('q');
value1 should then be "123".
I think you can't,but you can declare all param before required your js file same as:
<script type="text/javascript">
var q = 123;
var parameter1 = 450;
var parameter2 = 300;
</script>
<script src="http://example.com/embed.js"></script>
You could place the parameters in attributes of the <script> tag.
<script src="http://example.com/embed.js" q="123" parameter1="450" parameter2="300"></script>
You can access these parameters in embed.js with
document.currentScript.getAttribute('q');
document.currentScript.getAttribute('parameter1');
document.currentScript.getAttribute('parameter2');
Note: document.currentScriptdoes not work on IE.
For more info check this out.
You can access script tag as the last script tag if ask for it without waiting for document load.
~function() {
var s = document.querySelectorAll("script");
s = s[s.length-1];
console.log(s.src);
}();
I am quite new to Javascript. I wanted to get the filename and extension from a specific folder. For that i am using ActiveXObject and going to the folder using GetFolder and then enumerating through each individual files. The code is given below.
<html>
<script type='text/javascript'>
var myFileNameArray = new Array;
var myFileNameArray = new Array;
function ReadFromFile()
{
var i;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fsofolder = fso.GetFolder("C:\\Users\\Divya.R");
var colFiles = fsofolder.Files;
var fc = new Enumerator(colFiles);
for (; !fc.atEnd(); fc.moveNext() )
{
msg += fc.item() + ";";
}
myFilePathArray = msg.split(";");
for(i=0;i<=myFilePathArray.length;i++)
{
myFileNameArray[i] = myFilePathArray[i].split("\\");
}
document.write(myFileNameArray[0]);
}
</script>
<body onload='ReadFromFile()'>
</body>
</html>
I will get the complete file path in myFilePathArray from each array element i should get the filename. For that I am trying to split again based on '/' and then thought to get the arraylength-1 th element. However the last document write return be a blank page. It doesnt split the myFilePathArray. Please let me know what is wrong with this.
Regards,
Div
Since \ is an escape character it will be ignored. I have found a solution which worked for me. The code is given below.
var msg = "C:\\Users\\Divya.R\\Data.txt;C:\\Users\\Divya.R\\Test2.csv";
var regex = /\\/g;
var fileName="";
var FilePath = msg.replace(regex, "\\\\");
//document.write(FilePath);
var myArray1 = new Array;
var myArray2 = new Array;
myArray1 = FilePath.split(";");
myArray2 =myArray1[0].split("\\");
for(var i=0;i<=myArray1.length-1;i++)
{
myArray2= myArray1[i].split("\\");
fileName = fileName+myArray2[myArray2.length-1];
}
//alert(myArray2[myArray2.length-1]);
alert(fileName);
Regards,
Divya
A simple substr and lastIndexOf would suffice to get your parts:
var path = "C:\\Users\\Divya.R\\Data.txt";
var fileName = path.substr(path.lastIndexOf("\\") + 1);
var ext = path.substr(path.lastIndexOf('.') + 1); // txt
i have the following code snippet, where inside for loop the value to contain is not getting assigned, is this is the proper way to copy array to other.??
as here
var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
var groupParam = "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";
var grpNameArr = groupParam.split("#");
var groupcn= groupCondition.split("&");
var m=grpNameArr.length;
var contain=new Array();
var cmds=new Array();
var ii;
for(ii=0;ii<(m-1);ii++)
{
contain[ii] = groupCn[ii];
cmds[ii] = grpNameArr[ii];
}
If you want to clone an array you can use slice() method as mentioned in this page:
http://www.hardcode.nl/subcategory_1/article_414-copy-or-clone-javascript-array-object
var oldArray = ["mip", "map", "mop"];
var newArray = oldArray.slice();
your array declaration is wrong , it should be like :-
var groupcn=["All","All","All","All"];
var grpNameArr=["abc","def","ghi"];
you can use :
var contain=groupcn.concat();
var cmds=grpNameArray.concat();
So, after your edit, I see your problem was that you has some typo's in your variable names.
Replace:
var grpNameArr = groupParm.split("#");
var groupcn= groupCondtn.split("&");
With:
var grpNameArr = groupParam.split("#");
// ^ Missing `a` and `r`.
var groupCn= groupCondition.split("&");
// ^ Capital C ^ Missing `i`'s and `o`.
Old Answer
These 2 lines:
var groupcn = All,All,All,All;
var grpNameArr = abc,def,ghi;
Are probably your problem.
What you're doing there is assigning the variable All to a new variable groupcn, then declaring All as a new variable, 3 times.
var groupcn=All,
All, // new variable with the name `All`
All, // new variable with the name `All`
All; // new variable with the name `All`. These 3 override `All`
You'll need to initialize them like this:
var groupcn = [All,All,All,All];
var grpNameArr = [abc,def,ghi];
Other than that, assuming m is the length of groupcn, the code should work.
However, a shorter solution is to copy the arrays like this:
var contain = groupcn.slice();
var cmds = grpNameArr.slice();
Following mistakes were in the code
Using one loop for both the arrays. Since there length is not same two different loops should be used.
There was typo mistake in groupcn variable.
Check this code
<!DOCTYPE html>
<html>
<script>
function chk()
{
var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
var groupParam = "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";
var grpNameArr = groupParam.split("#");
var groupcn= groupCondition.split("&");
var contain=new Array();
var cmds=new Array();
var ii;
for(ii=0;ii<(groupcn.length-1);ii++)
contain[ii] = groupcn[ii];
for(ii=0;ii<(grpNameArr.length-1);ii++)
cmds[ii] = grpNameArr[ii];
alert("groupcn = "+contain);
alert("grpNameArr = "+cmds);
}
</script>
<body onload="chk()">
</body>
I am adding my Javsacript file in pages with different query strings in the script path like this:
Page1:
<script type="text/javascript" src="file.js?abc=123"></script>
Page2:
<script type="text/javascript" src="file.js?abc=456"></script>
Page3:
<script type="text/javascript" src="file.js?abc=789"></script>
In my Javascript file, how can I get the value of the "abc" param? I tried using window.location for this, but that does not work.
In case it helps, below is a function I use to find the value of a query string param:
function getQuerystring(key, defaultValue) {
if (defaultValue == null) defaultValue = "";
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
var qs = regex.exec(window.location.href);
if (qs == null)
return defaultValue;
else
return qs[1];
}
This is possible. See Passing JavaScript arguments via the src attribute. The punchline is that since scripts in HTML (not XHTML) are executed as loaded, this will allow a script to find itself as it is always the last script in the page when it’s triggered–
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
// myScript now contains our script object
var queryString = myScript.src.replace(/^[^\?]+\??/,'');
Then you just apply the query string parsing.
First, the technical answer: if you assign your script tag an ID, you can then grab its src and then parse out the query string.
<script id="whatever" type="text/javascript" src="file.js?abc=123"></script>
var path = document.getElementById('whatever').src;
// ...
With that answered, I'd like to voice my concern — this reeks of poor design decisions. Why are you including your script this way (with a querystring)? If you're trying to optimize your site (by having one large script that can be cached for subsequent pages), this approch is actually counter-productive because browsers will make a fresh request for the script file on each page due to the differing query string. The correct approach is to have one large shared file and then a small page-specific file on each page.
Since there is no more significant use of Internet Explorer. You can use document.currentScript and new URL, which return a string with the tag <script> in question.
const search = new URL(document.currentScript.src).search.substring(1)
const stringPreparation = decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')
const qs = JSON.parse('{"' + stringPreparation + '"}')
You can reduce this code to one line, but it is not recommended, let minifier scripts do that.
You can use the URL api and document.currentScript to retreive this`
const url = new URL(document.currentScript.getAttribute('src'));
const scriptParams = Object.fromEntries(url.searchParams)
console.log(scriptParams);
I have a quick and easy solution for extracting the query string from a js file using jQuery to grab the script tag source attribute and simply using two separate functions for parsing the JS file path and query string. Obviously, jQuery is required.
$(document).ready(function() {
var p = parseURL($('script[src*="thisfile.js"]').attr('src'));
console.log(p);
});
// Parse a URL into its parts
function parseURL(url)
{
var p = document.createElement('a');
p.href = url;
var obj = {
'protocol' : p.protocol,
'hostname' : p.hostname,
'port' : p.port,
'pathname' : p.pathname,
'search' : p.search,
'query' : p.search.substring(1),
'args' : parseStr(p.search.substring(1)),
'hash' : p.hash,
'host' : p.host
};
return obj;
}
// Parse a query string
function parseStr(string)
{
var args = string.split('&');
var argsParsed = {};
for (i = 0; i < args.length; i++)
{
var arg = decodeURIComponent(args[i]);
if (arg.indexOf('=') == -1)
{
argsParsed[arg.trim()] = true;
}
else
{
var kvp = arg.split('=');
argsParsed[kvp[0].trim()] = kvp[1].trim();
}
}
return argsParsed;
}