Specify style in URL query string - javascript

Suppose I have a web page
http://foo.com/bar.html
Is there any way I can provide a link to that page that, for sake of example, makes all <b> sections red?
I'm guessing I need some script in bar.html and a URL something like
http://foo.com/bar.html?style="b{color:red;}"
Is this possible and if so, is there a standard way to do it?

You can read the query string via location.search and then apply whatever logic you want to the string you get back.
Be careful not to open yourself up to an XSS attack.

why don't you try it with CSS?
inside example.css file:
br
{
color:red;
}

I would say the easiest and most abstract way would just be to append the style directly to the head. Again though, as stated, you may want to parse it and verify its proper format and avoid attacks. You'd be giving every web user direct access to your stylesheet in your head.
window.onload = function() {
if(document.location.search.indexOf('style=')>-1) {
var style = decodeURI(document.location.search.substring(document.location.search.indexOf('style=') + 6));
if(style.indexOf(',')>-1) { style = style.substring(0,style.indexOf(',')); }
var elem = document.createElement('style');
elem.type='text/css';
elem.innerHTML = style;
document.head.appendChild(elem);
}
};
Then you could add any and all style modifications to your URI like this ?style=body{background-color:blue;}%20b{color:red;}

You can customize javascript to do whatever you want. There's no pre-existing, universal way of doing this.
You could check document.location.hash to pull out a value and add a new style for b elements. Query-string parsing is a bit more difficult as it's not built into JS by default.

You could add a handler to a link element.
You can do it like this:
document.getElementById('clickme').onclick = function(){
var bolds = document.body.getElementsByTagName("b");
for(var i = 0; i < bolds.length; i++){
bolds[i].style.backgroundColor = 'red';
}
}
Demo: http://jsfiddle.net/maniator/HH2Cv/

Related

How to change CSS file using JavaScript?

I would ask how to change src of CSS using pure Javascript. I saw on internet that one guy used cookies for this, by i tried sth like this:
window.onload = function onload() {
setTimeout(function(){
document.styleSheets[1].href = "file:///C:/Users/Ma%C5%9Blan/Desktop/Site/bootstrap-3.3.6-dist/project1a.css";
}, 3000);
};
And it didn't work (i want to change CSS after 3 s, i know that actual localization is local, on my PC. Just trying :) ). I want to swap whole file.
Any ideas? If it's impossible in pure JS, show me jQuery way then.
Thanks!
document.styleSheets is a READ-ONLY property, so you won't be able to change the properties of that array.
What you want to do instead is get a list of all the <link> elements in the head, then either use a regex or conditional statement to get the element you are looking to replace, and use .href on that element.
E.G.
// get all links in the head (including CSS)
var allLinks = document.head.getElementsByTagName('link');
// find and replace the element
for (var i = 0; i < allLinks.length; i++) {
if ( allLinks[i].href = "old/url/to/css/file.css") {
allLinks[i].href = "file:///C:/Users/Ma%C5%9Blan/Desktop/Site/bootstrap-3.3.6-dist/project1a.css";
}
}

Javascript: match using dom loaded page

I am trying to grab all links from google search result using Chrome console.
First I wanted to get the dom loaded source. I tried below code.
var source = document.documentElement.innerHTML;
Now when I type source in console source it shows the correct dom loaded source. But if I run alert(source); It's showing default html source of page.
So problem is when I run below code
source.match(/class="r"><a href="(.*?)"/);
It is returning null, because variable source has the source code before dom loaded.
You can use DOM API (i.e. getElementsByTagName) to find all a tags in a page. Take a look:
var anchors = document.getElementsByTagName('A');
var matchingHrefs = Array.prototype.slice.call(anchors).filter(function(a) {
return a.className == 'r';
}).map(function(a) {
return a.href;
});
A
B
C
The Array.prototype.slice.call call turns node list into regular array.
Probably, you need to add /g flag to your regex to match globally.
Like this:
yourHtml.match(/href="([^"]*")/g)

Javascript variable equals specific URL

I'm trying to get this conditional statement to work, but having no luck
<body onload="HashTagInsert()">
function HashTagInsert() {
var hash="window.location";
if (hash==="http://www.address.com#anchor1")
{
document.getElementById("insert-text").innerHTML="<h2>Title</h2><p>body text</p>";
}
else if (hash==="http://www.url.com/foler/code/page.html#anchor2")
{
document.getElementById("insert-text").innerHTML="<h2>Title</h2><p>body text</p>";
}
else ()
{
document.getElementById("insert-text").innerHTML="something else text"
}
}
</body>
If you want the hash variable to be the value of the window.location object, then don't put quotes around the object name as that will turn it into a string literal.
var hash = window.location;
I recommend not calling the variable hash though, as that could be confused with window.location.hash, which contains the fragment ID component of the URL.
Don't add quotes around window.location.
var hash = window.location.href;
If you want to compare your current window location with some string you need to set the "hash" variable correctly:
var hash = window.location;
but I am not sure if I got your problem.
In case that your javascript can not set your html properly, there is also a timing problem. It depends when your javascript gets called. Before or after your DOM has been rendered. Because if your javascript is executed before your DOM (and your element '#insert-text') is rendered, you wont be able to select this DOM element.
And ... but this is perhaps just my opinion, is is pretty uncool to have masses of if / else if / else constructions in your code.
You might want to map some url and text so that you do not need to make your life harder than it is.
for example:
var html;
var mapping = {
"http://www.address.com#anchor1":"<h2>Yeah</h2><p>Baby</p>",
"http://www.address.com#anchor2":"<h2>Cool</h2><p>Tomato</p>",
"default": "<h2>Woops</h2><p>Honolulu rocks</p>"
}
mapping[window.location.href] ? html = mapping[window.location.href] : html = mapping['default'];
document.getElementById("insert-text").innerHTML=html;

Given a string of html code, how can I go through every tag and remove ones that is not in my whitelist (in JQuery)?

var whitelist = ['a','div','img', 'span'];
Given a block of HTML code, I want to go through every single tag using JQuery
Then, if that tag is NOT in my whitelist, remove it and all its children.
The final string should now be sanitized.
How do I do that?
By the way, this is my current code to remove specific tags (but I decided I want to do whitelist instead)
var canvas = '<div>'+canvas_html+'</div>';
var blacklist = ['script','object','param','embed','applet','app','iframe',
'form','input', 'link','meta','title','input','button','textarea'
'head','body','kbd'];
blacklist.forEach(function(r){
$(canvas).find(r).remove();
});
canvas_html = $(canvas).get('div').html();
Try this:
var whitelist = ['a','div','img', 'span'];
var output = $('<div>'+canvas_html+'</div>').find('*').each(function() {
if($.inArray(this.nodeName.toLowerCase(), whitelist)==-1) {
$(this).remove();
}
}).html();
// output contains the HTML with everything except those in the whitelist stripped off
try:
$(canvas).find(':not(' + whitelist.join(', ') + ')').remove().html();
The idea is to turn array of whitelist into "el1, el2, el3" format, then use :not selector to get the elements that's not in the whitelist, then delete.
This obviously could be expensive depending on the size of your html and whitelist.
Unfortunately, using jQuery to sanitize HTML in order to prevent XSS is not safe, as jQuery is not just parsing the HTML, but actually creating elements out of it. Even though it doesn't insert these into the DOM, in some cases embedded Javascript will be executed. So, for example, the snippet:
$('<img src="http://i.imgur.com/cncfg.gif" onload="alert(\'gotcha\');"/>')
will trigger an alert.

How do I target a url like this with CSS or JavaScript?

I have a video page that has filters for the videos. If I click on one of the filters (e.g. "music videos"), the url changes to something like this:
http://mysite.com/videos/?videofilter=music-videos
Unfortunately, there isn't a body class added or anything where I can easily target it by doing something like this:
body.music-videos { }
Is there a way to somehow target the url using CSS or JavaScript?
You could use Javascript's location.href to get the location, and work with it like a normal string.
But it would be much more recommended to server-side the body to have a class.
Presumably your page loads with that URL - can't you do somehting when you render the page to include something css-detectable?
I don't know if I understand your question. Are you trying to target a link with an href value? You should be able to target that with something like selector[src=URL] in css. If you're trying to target the body tag based on the URL I would create conditional scripts under if statements such as if(location.href=='url'){ document.getElementsByTagName("body").style.property="whatever" } . Hope this helps.
I'm not sure I understand...
So you click the filter options, which sends a query string to the URL. We can get the query string as such:
var qs = [];
var q = window.location.search.substring(1);
var p = q.split('&');
for(var i = 0; i < p.length; i++) {
var pos = p[i].indexOf('=');
if(pos > 0) {
var key = p[i].substring(0, pos);
var val = p[i].substring(pos+1);
qs[key] = val;
}
}
Then you simply access qs['videofilter']to get the value. From there, if it's doing nothing, well – you don't have a filter, you have check boxes. The only way to have a filter is to have some form of commonality by which to categorize them all. If you're wanting to do this through javascript and css, you could use that filter in a regex to find the specific tag whose innerHTML matches the value you got above, then determine the whole container's relationship( e.g. parent, grandparent, etc. ), and set that to display:none;
If you mean something else, please clarify.
This solution is Firefox only unfortunately:
From https://developer.mozilla.org/en/CSS/#-moz-document
#-moz-document url(http://www.w3.org/),
url-prefix(http://www.w3.org/Style/),
domain(mozilla.org)
{
/* CSS rules here apply to:
+ The page "http://www.w3.org/".
+ Any page whose URL begins with "http://www.w3.org/Style/"
+ Any page whose URL's host is "mozilla.org" or ends with
".mozilla.org"
*/
/* make the above-mentioned pages really ugly */
body { color: purple; background: yellow; }
}

Categories

Resources