5

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

1
  • Is this bookmarklet for personal use or for putting on a website?
    – Lekensteyn
    Commented Mar 11, 2011 at 18:54

3 Answers 3

6

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.

1
  • 1
    I need to support Firefox, Chrome and IE
    – Will Evans
    Commented Mar 11, 2011 at 18:54
6

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)})()
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?

2
  • @Will impossible to create a bookmarklet that is supported anywhere but IE to do what you want
    – mplungjan
    Commented Mar 11, 2011 at 18:58
  • Except there is a copy function in the chrome devtools Commented Jun 21, 2021 at 4:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.