gustavo
gustavo

Reputation: 11

Add links using javascript

I'm trying to add a link at the bottom of google's home page using javascript and greasemonkey in firefox, but I can't make it work:

// ==UserScript==
// @name testing greasemonkey
// @include http://*google.com/
// ==/UserScript==    

document.write('<a href="http://bing.com">Go to Bing</a> ');

Can anyone help me?

Upvotes: 1

Views: 322

Answers (2)

mplungjan
mplungjan

Reputation: 177860

Use DOM

var link = document.createElement("a");
link.href="http://bing.com";
link.innerHTML="Go to Bing"
document.body.appendChild(link);

For a more useful usage you could do this:

var link = document.createElement("a");
link.href="http://bing.com";
link.target="_blank";
link.onclick=function() {
  this.href="http://www.bing.com/search?q="+escape(document.getElementsByName("q")[0].value);
}
link.innerHTML="Do the same search in Bing"
document.body.appendChild(link);

Upvotes: 1

Detect
Detect

Reputation: 2069

It's probably too late for document.write. Try to add the element to the DOM.

var oNewA = document.createElement("a");
oNewA.setAttribute('href', 'http://bing.com');
var oText = document.createTextNode("Go to Bing");
oNewA.appendChild(oText);
document.body.appendChild(oNewA);

Upvotes: 4

Related Questions