I see in MathJax they include the script like this.
<script type="text/javascript" src="path-to-MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
Is there a way to get the config parameter in javascript?
The only way to get that URL is to search the current document and find that particular <script> tag and then get the .src property from the script tag and then parse it to get the config parameters.
Scripts are loaded into the global browser namespace and don't have any properties or variables that are unique to a particular script. You could use something like this:
function findScript(tagToMatch) {
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src.indexOf(tagToMatch) !== -1) {
// scripts[i].src is the full URL
return scripts[i].src;
}
}
}
And, then you could use that generic function to find your particular tag and parse out the config value like this:
function findConfig() {
var url = findScript("/MathJax.js?"), matches;
if (url) {
matches = url.match(/[&?]config=([^&$]+)/);
if (matches) {
return matches[1];
}
}
return null;
}
var cfg = findConfig();
And, here's a working snippet:
function findScript(tagToMatch) {
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src.indexOf(tagToMatch) !== -1) {
// scripts[i].src is the full URL
return scripts[i].src;
}
}
}
function findConfig() {
var url = findScript("/MathJax.js?"), matches;
if (url) {
matches = url.match(/[&?]config=([^&$]+)/);
if (matches) {
return matches[1];
}
}
return null;
}
document.write(findConfig());
<script type="text/javascript" src="path-to-MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
You can use regular expressions and plain-old-javascript to extract the config parameter, but if you're using jQuery there are more elegant ways of isolating the element you need.
function extractMathJaxConfig() {
var scripts = document.getElementsByTagName("script")
var regex = /config=([^&]+)/
for (var i = 0; i < scripts.length; ++i) {
var src = scripts[i].src;
if (src.indexOf("MathJax.js") != -1) {
var results = regex.exec(src);
if (results) return results[1];
}
}
}
console.log(extractMathJaxConfig());
JSFiddle: https://jsfiddle.net/vdqvjnbw/
You won't get that parameter via your script that you're requesting in that script tag, here's why:
The binary representation of the JS code will not be loaded into memory until the browser has pulled those bytes into the page. Meaning, that JS is basically just a text file out on the server until its downloaded by the browser and interpreted; the JavaScript has no behavior until then.
However, inside of your page -- if you'd like to strip that query param from the src attribute of your script tag -- you can do something like this:
function getURIComponents(uri) {
var a = document.createElement('a');
a.href = uri;
return {
origin: a.origin,
search: a.search
};
}
function getParams(uri) {
var c = getURIComponents(uri);
var pairs = c.search.split('?')[1].split('&');
var params = {};
for (var i = 0, len = pairs.length; i < len; i++) {
var pair = pairs[i].split('=');
var name = pair[0];
var value = pair[1];
params[name] = value;
}
return params;
}
getParams(document.getElementByTagName('script').src);
This [untested] code should give you an object containing a key config with what value has been set for it.
Hope this helps.
Related
I currently use this script:
wHandle.setNick = function (arg) {
userNickName = arg;
var fnicks = ["porno","ibne","amcık","amcik","piç","salak","orospu","pkk","sik","kürdistan","kurdistan","kÜrdistan","kürt","sikeyim","sıkeyim","götoş","yönetici","YÖNETICI","YONETICI","yonetici","admın","admin","yarah","yarrah","agario","sike","s1ke","anan"];
var nctr = arg.toLowerCase();
if(fnicks.indexOf(nctr) > -1) {
alert("Unknown Nickname!");
} else {
hideOverlays();
sendNickName();
wjQuery("#mini-map-wrapper").show();
userScore = 0
wjQuery(".btn-needs-nick").prop("disabled", false);
}
};
I wanted to make some kind of filter, so that it blocks these nicknames BUT it isn't covering all of my cases. For example it blocks porno but not pornoo
I want it to use if(contains).
You've essentially done your logic backwards. Instead of checking if the nickname is in your block list, you'd be better served checking if an element of your blocklist is in your nickname like so:
var nick = args.toLowerCase();
for (var i; i < fnicks.length; i++) {
if (nick.indexOf(fnicks[i]) != -1) {
//bad name!
}
}
well I would just loop through the array, and search if the argument you pass (nctr in that case) contains the current entry (fnicks[i]).
you can replace the console.log() by your usual alert()
var arg = "pornoo";
var fnicks = ["porno","ibne","amcık","amcik","piç","salak","orospu","pkk","sik","kürdistan","kurdistan","kÜrdistan","kürt","sikeyim","sıkeyim","götoş","yönetici","YÖNETICI","YONETICI","yonetici","admın","admin","yarah","yarrah","agario","sike","s1ke","anan"];
var nctr = arg.toLowerCase();
for(var i=0,c=fnicks.length;i<c;i++) {
if(nctr.indexOf(fnicks[i]) > -1) {
console.log('boom');
}
}
I am trying to strip duplicate query string parameters from the url. What am I doing wrong?
function stripUrlParams(url, parameter) {
//prefer to use l.search if you have a location/link object
var urlparts= url.split('?');
if (urlparts.length>=2) {
var prefix= encodeURIComponent(parameter)+'=';
var pars= urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i= pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
url = urlparts[0] + '?' + pars.join('&');
return url;
} else {
return url;
}
}
stripUrlParams('www.testurl.com?x=1&y=2&x=2');
//Should return "www.testurl.com?x=1&y=2".
http://jsfiddle.net/marcusdei/LnzsoLot/1/
Try this:
function stripUrlParams(url, parameter) {
//prefer to use l.search if you have a location/link object
var urlparts= url.split('?');
if (urlparts.length>=2) {
var stuff = urlparts[1];
pars = stuff.split("&");
var comps = {};
for (i = pars.length - 1; i >= 0; i--)
{
spl = pars[i].split("=");
comps[spl[0]] = spl[1];
}
pars = [];
for (var a in comps)
pars.push(a + "=" + comps[a]);
url = urlparts[0] + '?' + pars.join('&');
return url;
} else {
return url;
}
}
document.getElementById('choice').innerHTML = stripUrlParams('www.testurl.com?x=1&y=2&x=2');
//Should return "www.testurl.com?x=1&y=2".
Fiddle: http://jsfiddle.net/praveenscience/n8497sqL/
In your var var prefix= encodeURIComponent(parameter)+'=';, parameter is undefined.
Try to provide a value for it, and this will probably solve your issue by adding your 2nd param in your function call:
stripUrlParams('www.testurl.com?x=1&y=2&x=2', '');
The problem is: Your function does not remove duplicate URL arguments, it simply removes the parameter you pass to the method when you call it.
For example calling
stripUrlParams('www.testurl.com?x=1&y=2&x=2', 'x');
will strip all x parameters from the URL. You'll have to keep track of parameters that are in your URL already and remove them (or not copy them over), when you come across them a second time. Possible solutions have been provided in other answers already.
The above solution from #Praveen Kumar is good but its will not correctly handle if the multi-selection values or arrays are passed.
So I'm writing here a function with little changes the function is to be used with URI instead of full URL, just pass this part to this function x=1&y=2.
function stripUriParams(uri) {
var stuff = decodeURIComponent(uri);
var pars = stuff.split("&");
var finalPars = [];
var comps = {};
for (var i = pars.length - 1; i >= 0; i--)
{
spl = pars[i].split("=");
//ignore arrays
if(!spl[0].endsWith(']')) {
comps[spl[0]] = spl[1];
} else {
//this is array so enter it into final url array
finalPars.push(spl[0] + "=" + spl[1]);
}
}
for (var a in comps)
finalPars.push(a + "=" + comps[a]);
url = finalPars.join('&');
return url;
}
Input:
stripUriParams('pr1=2&pr1=3&pr2=1&arr[]=1&arr[]=2');
Output:
pr1=2&pr2=1&arr[]=1&arr[]=2
Whereas the output of Parveen's function would be something like
pr1=2&pr2=1&arr[]=1
PS) Why I didn't edit the above answer because I modified it for URIs instead of full URL.
I need to get a list of all font names that are available for use on the page via #font-face declarations (whether in external stylesheets or inline <style> elements). This is for a script that will be included on pages I do not control.
Ideally I'd like to do this without re-downloading all CSS files over AJAX and then parsing them.
But I can't use the new document.fonts API because I need this to be reasonably cross-browser (even IE7 if possible).
Is there any way to do this without downloading and parsing the CSS?
I think something like this would be a start:
var sheets = document.styleSheets,
sheet,
rule,
i, j;
for (i = 0; i < sheets.length; i++) {
sheet = sheets[i];
for (j = 0; j < sheet.rules.length; j++) {
rule = sheet.rules[j];
if (typeof(rule.cssText) !== 'undefined' && rule.cssText.indexOf("font-face") !== -1) {
console.log(rule.cssText); // you can parse the font name from rule.cssText here
}
}
Check below code, it might help
var ruleFontName = [];
$.each(document.styleSheets, function(sheetIndex, sheet) {
$.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
if (typeof(rule.cssText) !== 'undefined' && rule.cssText.indexOf("font-face") !== -1) {
var fntSrc = (rule.cssText. match(/src: *url\(([^;]+)\);/i) || ["", ""])[1];
var fntName = (rule.cssText.match(/font-family: *([^;]+);/i) || ["", ""])[1];
add(ruleFontName,fntSrc,fntName )
}
});
});
//checking if array values are not repeated
function add(arr, src, name) {
var foundName = arr.some(function (el) {
return el.fntName === name;
});
var foundSrc = arr.some(function (el) {
return el.fntSrc === src;
});
if (!foundName && !foundSrc) {
arr.push({ fntName: name, fntSrc: src });
console.log(arr);
}
}
JSFIDDLE : http://jsfiddle.net/hiteshbhilai2010/dpfpLyq1/47/
I would like to display a message on the page based on some value appearing in the URL. I have a known list of strings I'm looking for and the corresponding message. I cannot seem to get anywhere with the lookup / messaging. Could anyone pls kindly help? JavaScript only preferred, not jquery. Not that I the difference at this point ;)
Many thanks!
<div id="messagediv"></div>
Sample URLs to test:
<p>Campaign 1
<p>Campaign 2
<p>Campaign 3
<script>
(function () {
var params = window.location.search.substring(1).split('&'),
urlParams = {},
key, val;
for (var i = 01; i < params.length; i++) {
urlParams[params.split('=')[0]] = params.split('=')[1];
}
// querystring is ?utm_campaign=SpaCamp12458
// for instance, match URL query value SpaCamp12458 with the nums SpaComp key and show the corresponding text in the messagediv
var nums = {
defaultMessage: "Default Message",
"SpaComp": "Spas",
"PoolComp": "Recreation",
"BeachComp": "Outdoors"
}
for (var i in nums) {
if (nums.hasOwnProperty(i)) {
var found = false;
for (var j in urlParams) {
if (urlParams.hasOwnProperty(j)) {
if (urlParams[j].indexOf(nums[i]) === 0) {
document.getElementById("messagediv").innerHTML = nums[i];
found = true;
break;
}
}
}
if (!found) {
document.getElementById("messagediv").innerHTML = nums.defaultMessage;
}
}
}
})();
</script>
alert(line) alerts 'ac'
typeof(line) is 'string'
When I run line.charAt(0), charAt is not a function.
When line is 'http://www.google.com/', it works,
I think it's the UTF-8 encoding of the file that I opened...
How to make charAt work with UTF-8?
UPDATED:
http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/src/effective_tld_names.dat?raw=1 is in my extension's chrome folder as effective_tld_names.dat
To run the code:
authority = 'orkut.com.br';
lines = sc_geteffectivetldnames();
lines = sc_preparetouse(lines);
domainname = sc_extractdomainname(authority, lines);
The code:
function sc_geteffectivetldnames () {
var MY_ID = "my#email.com";
var em = Components.classes["#mozilla.org/extensions/manager;1"].
getService(Components.interfaces.nsIExtensionManager);
var file = em.getInstallLocation(MY_ID).getItemFile(MY_ID, "chrome/effective_tld_names.dat");
var istream = Components.classes["#mozilla.org/network/file-input-stream;1"].
createInstance(Components.interfaces.nsIFileInputStream);
istream.init(file, 0x01, 0444, 0);
istream.QueryInterface(Components.interfaces.nsILineInputStream);
var line = {}, lines = [], hasmore;
do {
hasmore = istream.readLine(line);
lines.push(line.value);
} while(hasmore);
istream.close();
return lines;
}
function sc_preparetouse(lines) {
lines = sc_notcomment(lines);
lines = sc_notempty(lines);
return lines;
}
function sc_notcomment(lines) {
var line;
var commentre;
var matchedcomment;
var replacedlines;
replacedlines = new Array();
var i = 0;
while (i < lines.length) {
line = lines[i];
commentre = new RegExp("^//", 'i');
matchedcomment = line.match(commentre);
if(matchedcomment) {
lines.splice(i, 1);
} else {
i++;
}
}
return lines;
}
function sc_notempty(lines) {
var line;
var emptyre;
var matchedempty;
var replacedlines;
replacedlines = new Array();
var i = 0;
while (i < lines.length) {
line = lines[i];
emptyre = new RegExp("^$", 'i');
matchedempty = line.match(emptyre);
if(matchedempty) {
lines.splice(i, 1);
} else {
i++;
}
}
return lines;
}
function sc_extractdomainname(authority, lines) {
for (var i = 0; i < lines.length; i++) {
line = lines[i];
alert(line);
alert(typeof(line));
if (line.chatAt(0) == '*') {
alert('test1');
continue;
}
if (line.chatAt(0) == '!') {
alert('test2');
line.chatAt(0) = '';
}
alert('test3');
checkline = sc_checknotasteriskline(authority, line);
if (checkline) {
domainname = checkline;
}
}
if (!domainname) {
for (var i = 0; i < lines.length; i++) {
line = lines[i];
alert(line);
if (line.chatAt(0) != '*') {
alert('test4');
continue;
}
if (line.chatAt(0) == '!') {
alert('test5');
line.chatAt(0) = '';
}
alert('test6');
checkline = sc_checkasteriskline(authority, line);
if (checkline) {
domainname = checkline;
}
}
}
return domainname;
}
It alerts 'ac', then 'string', then nothing.
UPDATED:
I'm thinking there is a difference between files opened with nsIExtensionManager and NSIIOService, because that real code doesn't work, but this test code works:
function makeURI(aURL, aOriginCharset, aBaseURI) {
var ioService = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
return ioService.newURI(aURL, aOriginCharset, aBaseURI);
}
URL = makeURI('file://C:/test/TLDs.dat');
// URL is a nsIURI; see nsIIOService::newURI for getting a string into a nsIURI.
var file = URL.QueryInterface(Components.interfaces.nsIFileURL).file;
// file is now a nsIFile
// open an input stream from file
var istream = Components.classes["#mozilla.org/network/file-input-stream;1"].
createInstance(Components.interfaces.nsIFileInputStream);
istream.init(file, 0x01, 0444, 0);
istream.QueryInterface(Components.interfaces.nsILineInputStream);
// read lines into array
var line = {}, lines = [], hasmore;
do {
hasmore = istream.readLine(line);
lines.push(line.value);
} while(hasmore);
istream.close();
// do something with read data
lines[0].charAt(0);
It's hard to tell what's going on without seeing any code, but remember that not all properties that evaluate as strings are really strings. A good example of this is the location object. Use of the object on its own will give you a string value, but you can't use any methods that are available to native strings on that string value.
// Although `window.location` returns a string, you cannot use String methods on it
alert(window.location.charAt(0)); // error
alert(window.location.href.charAt(0)); // no error
The same could be true of strings provided by external interfaces, such as plugins or ActiveX controls. The solution to this problem is to cast to a native string:
alert((""+window.location).charAt(0)); // auto casting with concatenation
alert(String(window.location).charAt(0)); // with the String() constructor
alert(window.location.toString().charAt(0)); // with toString()
At least the first two of those methods should solve your problem (replace window.location with your var). If not, try posting some code so we can get a better idea of what's happening.
Looking at your code, I can only assume that what I said above is correct. The readLine method returns a line object that contains the non-native string property value (which is rather odd, considering). I would suggest editing your code to look like this:
function sc_geteffectivetldnames () {
var MY_ID = "my#email.com";
var em = Components.classes["#mozilla.org/extensions/manager;1"].
getService(Components.interfaces.nsIExtensionManager);
var file = em.getInstallLocation(MY_ID).getItemFile(MY_ID, "chrome/effective_tld_names.dat");
var istream = Components.classes["#mozilla.org/network/file-input-stream;1"].
createInstance(Components.interfaces.nsIFileInputStream);
istream.init(file, 0x01, 0444, 0);
istream.QueryInterface(Components.interfaces.nsILineInputStream);
var line = {}, lines = [], hasmore;
do {
hasmore = istream.readLine(line);
lines.push(String(line.value)); // <--- or ""+line.value
} while(hasmore);
istream.close();
return lines;
}
I found URI Parsing for Firefox in MDC.
https://developer.mozilla.org/en/Code_snippets/URI_parsing
Somehow, it's not appearing on Google.