When I call the script via
<script type="text/javascript"
src="include/javascript/test_something.js?v=1128557"></script>
how do I refer to the variable V passed in the html?
Thanks in Advance!
The most simple way would be to use a server side technology. This is in php.
<?php
$v=1128557;
?>
<script type="text/javascript">
//This will make this value available to javascript too
var val=<?php=$v?>;
</script>
<script type="text/javascript"
src="include/javascript/test_something.js?v=<?php=$v?>"></script>
...
...
...
<div id='baba<?php=$v?>'>
...
...
</div>
This will be translated to the following html
<script type="text/javascript">
//This will make this value available to javascript too
var val=1128557;
</script>
<script type="text/javascript"
src="include/javascript/test_something.js?v=1128557"></script>
...
...
...
<div id='baba1128557'>
...
...
</div>
Get it from the src attribute of the last script element in your page:
var scripts = document.getElementsByTagName("script");
var src = scripts[scripts.length - 1].src;
var v = null;
if (/\?v=(.+)$/.test(src)){
v = RegExp.$1;
}
If it's the first script tag on the page, you can do something like:
var thescripttag = document.getElementsByTagName('script');
var v = thescripttag[0].src.replace(/^[^\?]+\??/,''); //gets everything after the '?'
If it's not the first script tag, you can change [0] to be whichever one it is, or try assigning an id to the script tag (untested).
You can find the appropriate script tag by looking for the desired filename and get the parameters off that .src URL.
function findScriptParams(fname) {
fname = "/" + fname + "?";
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var pos = scripts[i].src.indexOf(fname);
if (pos != -1) {
return(scripts[i].src.substr(pos + fname.length));
}
}
}
And then you would invoke it like this:
var params = findScriptParams("test_something.js");
if (params) {
// process the params here
}
Change it to
<script type="text/javascript"
src="include/javascript/test_something.php?v=1128557" />
Then create the script test_something.php to be
<?php
echo "var queryString='" . $_SERVER[`QUERY_STRING] . "'\n;";
?>
... rest of javascript here
You can even perform error checking/parsing of the query string using PHP or just get Javascript to do this.
You should do the following:
var scripts = document.getElementsByTagName('script');
var data = {};
for (var i = 0; i < scripts.length; i ++) {
if (!scripts[i].src) {
continue;
}
var value = scripts[i]..substring(scripts[i].indexOf('?') + 1);
var params = value.split('&');
for (var i = 0; i < params.length; i ++) {
params[i] = params[i].split('=');
data[params[i][0]] = params[i][1];
}
}
EDIT: Just incorporated some of the tips from others, and added them to my own answer.
JavaScript only has access to URL data for the page it's being executed on via window.location. It does not have access to any HTTP request variables passed to the javascript file itself unless the web server explicitly serializes it to JavaScript in the output.
One hack/workaround would be to find the script tag, get the src attribute, parse the URL and extract the GET parameters you need.
function getParamsFor(script) {
var params, anchor, paramArray, keyVal, tag, scripts;
scripts = document.getElementsByTagName("script");
// Make sure [].filter exists beforehand
tag = Array.prototype.filter.call(scripts, function (e) {
return e.src.indexOf(script) > -1;
})[0];
if (tag) {
anchor = document.createElement("a");
anchor.href = tag.src;
paramArray = anchor.search.substring(1).split('&');
params = {};
for(var i = 0; i < paramArray.length; i++) {
keyVal = paramArray[i].split('=');
params[unescape(keyVal[0])] = (typeof keyVal[1] != "undefined") ? unescape(keyVal[1]) : keyVal[1];
}
return params;
}
}
var o = getParamsFor("test_something.js");
o.v; // 112..
Related
I made a chrome extension where my popup button calls a script. The other script uses jQuery but I get an error saying jQuery is not defined.
My popup.html:
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
My popup.js:
document.addEventListener('DOMContentLoaded', function() {
var login = document.getElementById('record');
login.addEventListener('click', function() {
chrome.tabs.executeScript({file: 'markStudents.js'});
});
});
myScript.js:
var arrays = []
$.get('Attendance.txt', function(data){
var splitted = data.split("\n"); // --> should return an array for each line
// Loop through all lines
for(var i = 0; i < splitted.length; i++)
{
var line = splitted[i];
// Now you could remove [ and ] from string
var removed = line.replace('[','').replace(']','');
var refined = removed.replace(' ', '');
// Now you can split all values by using , delimiter
var values = refined.split(',');
var array = [];
// Now you can iterate through all values and add them to your array
for(var c = 0; c < values.length; c++)
{
var value = values[c];
array.push(value);
}
arrays.push(array);
}
});
var present = arrays[0];
console.log(present);
var absent = arrays[1];
console.log(absent);
var user = present[0];
var pass = absent[0];
var loginField = document.getElementById('fieldAccount');
var passwordField = document.getElementById('fieldPassword');
loginField.value = user;
passwordField.value = pass;
var loginForm = document.getElementById('btn-enter-sign-in');
Is there any way to include my jquery.js in myScript.js?
Console Error
Just import jquery before you import popup.js
Like this
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
Inside Your popup.js, when you load markStudents.js which uses jQuery, you'd again have to load jQuery before same
Like this
document.addEventListener('DOMContentLoaded', function () {
var login = document.getElementById('record');
login.addEventListener('click', function () {
chrome.tabs.executeScript(null, { file: "jquery-3.4.1.min.js" }, function () {
chrome.tabs.executeScript(null, { file: "markStudents.js" });
});
});
});
Just reorder your script tags and put jQuery before your popup.js. That way it will be loaded when you try to call it.
yo can use this code to include another jquery file in your jquery:
$.getScript("file address");
like this:
$.getScript("/assets/pages/scripts/ui-blockui.min.js");
I want to find the script path of my own js file in itself.
So I want have as a string "C:\files\MyProject\MyScripts\MyJavaScript.js".
How is that possible?
You can try (Jquery):
var myScriptDetails = $('script');
myScriptDetails will contain details regarding the script, including its location.
Try this solution. I think this is exactly what u want :)
Put this code in each of your linked script file
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 );// you can save these in any variable also
I tested it with this HTML code:
<!DOCTYPE html>
<html>
<head>
<title>testing...</title>
<script type="text/javascript" src="test.js"></script>
<script type="text/javascript" src="js/test2.js"></script>
<script type="text/javascript" src="../test3.js"></script>
</head>
<body>
content area
</body>
</html>
And found this Output in console:
file:///D:/workspace/dbshell/www/test.js file:///D:/workspace/dbshell/www/ test.js:6
file:///D:/workspace/dbshell/www/js/test2.js file:///D:/workspace/dbshell/www/js/ test2.js:6
file:///D:/workspace/dbshell/test3.js file:///D:/workspace/dbshell/ test3.js:6
Special thanks to meouw..
Hope this helps..
here is how I made it:
function ScriptPath() {
var scriptPath = '';
try {
//Throw an error to generate a stack trace
throw new Error();
}
catch(e) {
//Split the stack trace into each line
var stackLines = e.stack.split('\n');
var callerIndex = 0;
//Now walk though each line until we find a path reference
for(var i in stackLines){
if(!stackLines[i].match(/http[s]?:\/\//)) continue;
//We skipped all the lines with out an http so we now have a script reference
//This one is the class constructor, the next is the getScriptPath() call
//The one after that is the user code requesting the path info (so offset by 2)
callerIndex = Number(i) + 2;
break;
}
//Now parse the string for each section we want to return
pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/);
}
this.fullPath = function() {
return pathParts[1];
};
this.path = function() {
return pathParts[2];
};
this.file = function() {
return pathParts[3];
};
this.fileNoExt = function() {
var parts = this.file().split('.');
parts.length = parts.length != 1 ? parts.length - 1 : 1;
return parts.join('.');
};
}
Client-side you can't access the physical path. You can get the src attribute of the script tag though.
Server-side you can get the physical path. For example (C#):
Path.GetFullPath(path)
For finding full path of URL in JavaScript use this location.href
If you can define absolute path of server as constant variable,
you can do it by casting from window.location.href. remove host prefix window.location.host from window.location.href and prepand with server's absolute path.
Try:
console.log(window.location.href);
I originally posted this How can I load js into my templates with Meteor/handlebars.js?
and thought I had a solution to my issue. I was wrong. I have some external js I want to load as well as an internal script. I tried placing the scripts in a template alone for example:
<template name="myscripts">
<script src="myexternalscript"></script>
<script src="anotherexternalscript></script>
<script src="anotherexternalscript"></script>
<script>
//internal script code here
</script>
</template>
then on the template with the html I want those scripts to affect, which contains html named "myothertemplate", I added
{{myscripts}}
to the bottom of those elements where I wanted it to load. Then that template which contains the html elements and the {{myscripts}} which I want to load the JavaScript, is loaded on my main page in the body {{>myothertemplate}}. I run my project, localhost:3000 and get no errors. I see the scripts I wanted there on the page where I wanted them as well but they don't work. They have no affect on the page. I tried taking the internal JavaScript and saving it as a JavaScript file as well as the external JavaScript files however this is not working either. This is an example of what I want:
<!--HTML here-->
<!--some elements here
after the last div on this template page, I wanted to add my scripts.-->
<div>
</div>
<script src="some external script"></script>
<script src="some external script"></script>
<!--Now my internal script-->
<script>
(function() {
// Base template
var base_tpl =
"<!doctype html>\n" +
"<html>\n\t" +
"<head>\n\t\t" +
"<meta charset=\"utf-8\">\n\t\t" +
"<title>Test</title>\n\n\t\t\n\t" +
"</head>\n\t" +
"<body>\n\t\n\t" +
"</body>\n" +
"</html>";
var prepareSource = function() {
var html = html_editor.getValue(),
css = css_editor.getValue(),
js = js_editor.getValue(),
src = '';
src = base_tpl.replace('</body>', html + '</body>');
css = '<style>' + css + '</style>';
src = src.replace('</head>', css + '</head>');
js = '<script>' + js + '<\/script>';
src = src.replace('</body>', js + '</body>');
return src;
};
var render = function() {
var source = prepareSource();
var iframe = document.querySelector('#output iframe'),
iframe_doc = iframe.contentDocument;
iframe_doc.open();
iframe_doc.write(source);
iframe_doc.close();
};
var cm_opt = {
mode: 'text/html',
gutter: true,
lineNumbers: true,
};
var html_box = document.querySelector('#html textarea');
var html_editor = CodeMirror.fromTextArea(html_box, cm_opt);
html_editor.on('change', function (inst, changes) {
render();
});
cm_opt.mode = 'css';
var css_box = document.querySelector('#css textarea');
var css_editor = CodeMirror.fromTextArea(css_box, cm_opt);
css_editor.on('change', function (inst, changes) {
render();
});
cm_opt.mode = 'javascript';
var js_box = document.querySelector('#js textarea');
var js_editor = CodeMirror.fromTextArea(js_box, cm_opt);
js_editor.on('change', function (inst, changes) {
render();
});
var cms = document.querySelectorAll('.CodeMirror');
for (var i = 0; i < cms.length; i++) {
cms[i].style.position = 'absolute';
cms[i].style.top = '30px';
cms[i].style.bottom = '0';
cms[i].style.left = '0';
cms[i].style.right = '0';
cms[i].style.height = '100%';
}
/*cms = document.querySelectorAll('.CodeMirror-scroll');
for (i = 0; i < cms.length; i++) {
cms[i].style.height = '100%';
}*/
}());
</script>
$.getScript('/myscript.js') worked.
I need to add an external javascript file to the <head> section of a website - one file when on the Staging server, and a different one for production.
So far I have this, but I get an error: 'return' outside of function
<script type="text/javascript">
var pathOrigin = window.location.origin;
var headtg = document.getElementsByTagName('head')[0];
if (!headtg) {
return;
}
var linktg = document.createElement('script');
if (pathOrigin.toLowerCase().indexOf("staging.server.com") >= 0) {
linktg.src = '/script-staging.js';
} else {
linktg.src = '/script-production.js';
}
headtg.appendChild(linktg);
</script>
What am I missing?
Thanks.
Return - Specifies the value to be returned by a function.
That means the error you got from the browser is correct. Your returnstatement is not part of a function, but of the global scope. You wil either have to skip using the return statement and use simple variable assingment like in #Azzy's answer, or encapsulate it in a function like so:
function getHead() {
var headtg = document.getElementsByTagName('head')[0];
if (typeof headtg === 'undefined') {
return; // will break the function
} else {
var linktg = document.createElement('script');
if (pathOrigin.toLowerCase().indexOf("staging.server.com") >= 0) {
linktg.src = '/script-staging.js';
} else {
linktg.src = '/script-production.js';
}
headtg.appendChild(linktg);
};
};
getHead(); // don't forget to initialize the function
//or you could do:
element.onload/onclick/on<whatever_event> = getHead();
To me it is also not clear what you want to return, unless you simply want to stop script execution; citing from MDN:
If the expression in return [expression] is omitted, undefined is returned instead.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
NB: Check this why it is safer to use the typeofstatement than a simple !mark to check if something exists: Check if object exists in JavaScript.
EDIT: For a very simple use case of the return statement, you can check out this fiddle I made which is basically a counter that will output an error when it reaches 100.
Where place this code? Are you sure that the path is correct?
Another method to add js file into head is this method:
<head>
....
<script type="text/javascript">
var pathOrigin = window.location.origin;
var path = "";
if (pathOrigin.toLowerCase().indexOf("staging.server.com") >= 0) {
path = '/script-staging.js';
} else {
path = '/script-production.js';
}
document.write( '<script type="text/javascript" src="' + path + '"><\/script>' );
</script>
.....
</head>
<html>
<head>
<script type='text/javascript'>
var path = window.location.origin
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
if (path == 'local'){
fileref.setAttribute("src", 'file:///D:/JS/jquery.js')
}
else{
fileref.setAttribute("src", 'file:///D:/JS/jquery.js')
}
document.getElementsByTagName("head")[0].appendChild(fileref)
//list all the js loaded dynamically
var scripts = document.getElementsByTagName('script');
console.log(scripts);
</script>
</head>
<body>
<p>test</p>
</body>
</html>
To load script dynamically, you can try out this..
The javascript error "return statement outside of function" means you've created a code fragment that is not allowed to exist outside of a function definition.
Or any other tags :)
for eg.
<head>
<title>page...</title>
<script> var a = 'abc'; </script>
<script src="foo.js" type="text/javascript"></script>
</head>
<body>
...
<script src="foo2.js"></script>
</body>
(this string is a response from a ajax call)
I want to get a array with 3 strings:
<script> var a = 'abc'; </script>
<script src="foo.js" type="text/javascript"></script>
<script src="foo2.js"></script>
How can I do that?
Define: outerHTML function (taken from here)
jQuery.fn.outerHTML = function(s) {
return (s) ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
}
Then assume your response is stored in data you can do:
$(data).filter("script").each( function(e) {
// do something with $(e).outerHTML()
} );
Use a regular expression with the pattern <script[^<]*</script>.
You can try something like:
function getScriptsAsText() {
var div = document.createElement('div');
var scripts = [];
var scriptNodes = document.getElementsByTagName('script');
for (var i=0, iLen=scriptNodes.length; i<iLen; i++) {
div.appendChild(scriptNodes[i].cloneNode(true));
scripts.push(div.innerHTML);
div.removeChild(div.firstChild);
}
return scripts;
}
It returns a array of the current script elements as text, including their start and end tags.
You might also try outerHTML, but it's not that widely supported.