4

How would I get the current URL with a javascript code that could be used in a bookmarklet? This code isn't working:

javascript:copy(window.location.href);

It needs to copy it to the clipboard. I need to support Firefox, Chrome and IE

Will Evans
  • 207
  • 2
  • 10
  • 20

3 Answers3

4

To get the URL from any legit browser (Opera, Chrome) with a bookmarklet:

javascript:(function(s){try{s=document.selection.createRange().text}catch(_){s=document.getSelection()}prompt('','\n'+location+'\n'+s)})()

If you want to add the Page Title:

javascript:(function(s){try{s=document.selection.createRange().text}catch(_){s=document.getSelection()}prompt('',document.title+" "+'\n'+location+'\n'+s)})()
3

What about a dialog from which you can copy the current URL?

javascript:void(prompt("URL:", location.href))

The void part prevents the browser from navigating away when pressing OK or Cancel.

Putting the URL into the clipboard takes more work, and differs on distinct browsers. If you really want to put the data in the clipboard, mention the browsers you need to support.

Lekensteyn
  • 58,351
  • 21
  • 146
  • 179
0

There is no built-in function in JS called copy. If there is one in the page, then it should work. So the page would need this code

How do I copy to the clipboard in JavaScript?

Community
  • 1
  • 1
mplungjan
  • 134,906
  • 25
  • 152
  • 209