0

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?

3
  • 1
    why this way and not with CSS? Commented Dec 7, 2011 at 15:32
  • @T9b, user might want to highlight stuff on external page (my assumption) Commented Dec 7, 2011 at 15:47
  • @T9b The destination document is always the same - I want different parts of it to be highlighted depending on the referrer's href. Commented Dec 7, 2011 at 20:40

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

why don't you try it with CSS?

inside example.css file:
br 
{
color:red;
}

Comments

1

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;}

1 Comment

Regarding attacks - what's the worse that could happen? As it happens this is not for public consumption (for now) so it's a moot point.
0

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.

1 Comment

@paperjam Passing code in the URL is never common. And it shouldn't be either
0

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/

1 Comment

So this is script at the source URL?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.