Hacker News new | past | comments | ask | show | jobs | submit login
Clipboard.js: Modern Copy to Clipboard (github.com/zenorocha)
304 points by jellekralt on Sept 30, 2015 | hide | past | favorite | 106 comments

Text field autoselection and programs being 'helpful' by copying things to the clipboards is one of the banes of my life. I wish there was a way to just disable all this, globally. If I want something selected, I'll select it myself, thanks.

My problem with text field autoselection is that it's wrecking my muscle memory of how to interact with text fields. My reflexes know that a single click places the cursor, a double click selects a word, and a triple click selects a line... except when the text field has autoselect turned on, which I can only find out after I've committed to the action. And they all behave slightly differently.

Example interaction:

- click on text field to place cursor.

- text field autoselects. I swear.

- click again to place cursor.

- hasn't been long enough since the last click, which means it's interpreted as a double click.

- text field selects word. I swear.

At this point I'll either force myself to wait for a second or so, to make the interaction time out, and then click again, or else I'll be too impatient and the madness continues as my third click is interpreted as a triple-click.

Seriously, wish there was a way to make this all stop. If I want my text fields selected, I'll do it myself, thanks.

Thanks for giving voice to my pain. Phone number input boxes like to torture me - the ones conveniently divided into three boxes for the three parts of the number. I like to use the keyboard. I tab into the first box, enter my area code, hit tab to go to the next box. But some helpful javascript has already put my cursor into the "next" box, which means I'm now in the third box, and need to back up. Something designed (I guess) to save time has made it take three times as long to fill out the form.

The next time, I remember and decide to be clever. After entering the area code, I wait. But this website doesn't have the evil javascript. The time-saving javascript on the first site has made filling out the form on the innocent website take three times as long.

> Phone number input boxes like to torture me - the ones conveniently divided into three boxes for the three parts of the number.

If you are a web developer, and you do this: stop.

This works for the North American numbers only. Get a user from the UK and you'll have to undo all this anyways.

Not to mention the complaint in parent's comment, that you can no longer copy/paste, plus the inclusion of javascript to skip to the next box (or the lack thereof) is confusing from a UX perspective.

Allow phone numbers to be entered in any format in a simple text box.

If you want, apply formatting after the fact based on the country, though I think this is even not a good idea. In some cases, the phone number won't be from the same country as the user (with VoIP and mobile, phone number locality is no longer a thing). Dialing formats are also a source of confusion, eg: do you include or require country code?

If there was a Firefox extension that simply disabled 100% of the ability to control or influence the selection, I'd install it in a second.

Manipulating the selection is probably a specific case of the larger problem of terrible, incomplete reimplementations of UI that already exists. This inevitably ends up demonstrating the exact gap between what user environment is, and what the webpage author believes it ought to be.

From a quick glance it seems quite possible to make such extension: simple dark prototype crippling for inputs and textareas like

    Selection.prototype.addRange = HTMLTextAreaElement.prototype.select = HTMLInputElement.prototype.select = function(){ console.info(this,' arificial selection disabled, sorry.') }
If you use some userscript manager, try it with https://greasyfork.org/en/scripts/12762-disable-arificial-se...

Hate to be that guy but just wanted to point out the typo in the console message/userscript title:

"arificial" should be "artificial" (missing 't').

Hanks for pointing out, good catch! Fixed in userscript, also updated it a bit. Not able to fix it here. Seems like quite frequent mistype BTW :]

Oh, cool! Thanks!

NoScript? If a website doesn't work without JS then is the site worth your time?

GitHub repo URL field got me swearing every single time.

Problem is, even when I'm doing as the field expects me to (as if it had a personality) it does not work, because xterm. So sometimes I end up pasting (ctrl+v) it into the URL bar and copying (=selecting) it again, the old fashioned way. :(

More often than not I don't even bother anymore and type the URL myself.

Any repo’s browser’s address bar URL will work as a git clone URL too, if that’s easier for you.

Text fields that auto select are annoying, but all of the examples provided here only copy if you click a button.

When there is a long string it is so much easier to just click a button instead of manually selecting the string. Yes sometimes the string is in its own field so you can use Cmd-A but a lot of times it isn't. And overwhelmingly, when someone took the time to think about what would need to be copied, and made it easier, the whole site/tool/process is much better designed.

There are legitimate cases to use something like this;

for example, our organisation has a 'secret server', a centrally audited webserver which stores passwords and controls who can access which passwords.

Personally I think the implementation is shitty.. but without displaying the password in cleartext, copying directly to the clipboard is a preferred solution.

(even if you can potentially mis-paste.)

Is there really any problem with displaying them, after a warning screen of some sort?

I'm not sure, but for me it 'feels' wrong.

since it's not quantifiable I can't really argue against it.. it's just a feeling.

It is annoying on the open web, and it is usually abused for news sites paywalls' to disable copying or adding boilerplate.

However, it can be useful for web applications. I got a requirement in an internal app to add a button to copy some text in an administrative application. That got scrapped due to the work required to do it reliably without flash.

i loathe confluences code boxes because of autoselect.

i often only want some lines from it... guess what? it selects the hole thing every time you try to explicitly select a small part of it (as in dragging the mouse while clicking over one word = whole document selected)

This one is the most annoying to me. For example if I want to use some analytics code but have a plugin or third party (segment.io) that I want to hand off just the "ID" to. If I try to select just the ID as soon as I release the mouse it select the whole thing. I have to copy it all into my note app (nvALT) then select want I want then delete all of it because I have no real desire to save it all as a note. Very irritating.

Hitting CMD+C while selecting the fragment usually works for me.

Also, it breaks select + middle-click paste into e.g. vim. The Google Analytics key, for instance, I have to copy into another textbox and then reselect and paste into vim.

To paste X clipboard into vim: "+y (if you are using gvim) or i and then ctrl-shift-v (if you are using vim in gnome-terminal).

I used to be a heavy user of select-middle-click copy & paste. But this method of interaction seems to be increasingly broken with each new Firefox release, even without extra Javascript magic.

"+p to paste of course :) That also works in a terminal so you don't have to use ctrl-shift-v.

I hate this kind of stuff too but to mitigate this issue you can press <HOME> or <END> on the keyboard.

I agree. Also maybe someone with great UI skills can remember to set a proper damn tab order.

Thank you for saying this.

I was thinking -- why isn't this more common?

Then I read the bottom of the readme, and noticed safari was holding back webdev once again.

I've been casually following this for the last 5 years and it seems almost too convenient that safari is regularly behind on mission critical features.

More common? It shouldn't exist at all. The potential use cases for manipulating the selection are at best a minor feature and sometimes a serious usability bug.

Stop trying to give webpages control - any control at all - over the browser UI. The page gets to control just that (the page) and the framework around that page (the browser). Any violation of this a potential security problem. Any time the demarcation between "remote page" and "browser UI" is blurred, problems such as "phishing" attacks become easier.

If you want fancier UI than is possible from a web page, write a native app.

    Any time the demarcation between "remote page" and 
    "browser UI" is blurred, problems such as "phishing" 
    attacks become easier.
Hugely important; largely ignored.

Unfortunately, people whose training and experience exists only inside a browser either don't or can't see beyond those confines and the result is reimplementing perfectly adequate external functionality.

This is indeed a nice argument.

Sometimes I am doing something on the CLI and go back to the terminal and paste a text I copied from somewhere.

If the text is multiline my terminal will consume the lines without requiring an extra 'enter / return' key press.

Another possibility is copying something to web mail client without noticing there's something suspicious about it (JS isn't the concern here anymore nowadays, but loading stuff like images is a privacy concern).

However, this issue MUST be fixed at browser level. And when used without destroying user expectations / UX, this plugin is useful.

Malicious attacks are going to happen anyways if the browser permit such action to happen, so don't blame the plugin or the plugin writer. The browsers are broken. Ask the major browser developers to either never allow it to happen (like Safari does) or ask them to ask for permission (like for webcams) or add a confirmation modal.

re: browser support (which is where this problem should be fixed)

A trivial compromise that would be even easier to use than the current javascript/selection stuff would be a "copy to clipboard" variant of the <button> tag. Something like this should satisfy the use-cases where this clipboard nonsense is occasionally useful:

      <input name="copy_souce" type="text" value="xyzzy" />
      <button type="clipboard" value="copy_source"
              name="Copy To Clipboard" />
This wouldn't require any Javascript, and leaves the clipboard entirely under the control of the user where it belongs.

This could even be extended to allow copying of the various types of input tags, and if you wanted to get fancy, the button could reference an #id and copy that element's textContent (or innerHTML).

Or people could .. You know... Use their platforms existing copy functionality.

I know it's only existed on desktop computers since the Apple Lisa, and 30 years isn't very long for people to grasp the concept of copy and paste without a button to do it, but I have faith in people.

This button couldn't be customized, otherwise it's useless as someone could easily get away with hiding it / showing only a small portion of it where someone could click without even noticing / etc.

Maybe a small modal-like confirmation that can be placed anywhere on the viewport and is actually on top of everything natively (like Safari's copy/paste on iOS).

Of course, this modal-like confirmation must not be customized or its effect is useless.

Or let's just forget entirely and remove the functionality from the browsers.

An HTML5 page with no stylesheet or javascript is hugely functional, legible, and responsive, adapting itself to any device. If there is a problem with a website it's because a "web designer" or front-end developer broke it.

This seems to be a civil war taking place purely amongst software developers. Some developers want the web to be used for hypertext documents as it was originally intended, and others want it to be used for anything for which there is demand amongst a sizable group of people, technical and non-technical alike. I see the appeal of the first viewpoint, and it's likely I would share it if I had the luxury of working on non-web software, but as it is, most of us go where the users are and work on what the users want, and that question has been settled: they want rich functionality that looks nice and is delivered through the web on their desktop and a mix of web and native apps on mobile. Only other programmers (and only a small subset of programmers at that) complain about javascript and stylesheets. In most cases, it doesn't make sense to pander to such a tiny audience.

I think the situation is more nuanced than that: users may not know the terms to complain about JavaScript and stylesheets but they know when a page is slow or broken.

The discussion really should focus on how well apps degrade, which is really reaffirming that progressive enhancement is still the best approach to building web apps. While only a small percentage of users have intentionally disabled JavaScript entirely, it's effectively disabled for everyone while it's downloading and a larger percentage of users (particularly on mobile) will have errors which prevent those downloads entirely. If you build a rich application which still has the core functionality working, you've done a much better job than the people who make sites which take minutes or don't even render when their shiny framework hits a non-perfect network connection.

This is a really good point, and the better conversation to have than broad brush dismissal of anything but raw hypertext like the comment I replied to. Graceful degradation is a user-friendly, competitive, and all around fantastic feature. It is also expensive, and may or may not belong at the top of the list of things to optimize to improve user experience. Eliminating everything but raw hypertext may be a cheaper solution, but it isn't a good one.

I did not advocate eliminating anything but raw hypertext. I like CSS and javascript when they are used well. I like web apps.

Fair enough! I misread.

Phishing is really more about web pages impersonating other web pages. I disagree that this functionality enables or facilitates phishing.

Funny. I find Safari leaps ahead of Firefox, and even further ahead of Chrome, when it comes to browser performance (CPU use, memory footprint, and especially battery life), with snappier scrolling and animations and fewer weird graphical glitches or mouse/keyboard interaction bugs. For my own browsing habits, Firefox is very sluggish, and Chrome is completely unusable: it just can’t handle the load and brings my whole computer to a crawl. The Safari user interface also feels much more platform-native and predictable (though it has unfortunately copied several Chrome UI elements in the last few years, which I think make the basic UI worse than ~5 years ago), and I don’t constantly feel like someone is trying to gather and analyze my keystrokes or sell me out to advertisers. (I don’t have a Windows machine, so I couldn’t tell you what IE is like these days.)

Maybe there’s just a focus on different things between vendors: Google has tons of 20%-time engineers pushing new half-baked features in every direction (yes this is a bit of a caricature), while Apple is taking a more measured approach with a focus on performance and reliability.

> (...) while Apple is taking a more measured approach with a focus

> on performance and reliability.

Good luck then trying to do anything complex with video and audio on iOS Safari. I've seen many weird quirks and bugs, strange limitations (videos always playing fullscreen on iPhone) and even browser crashes.

And considering reliability: wouldn't you agree that we would be better of using a native solution for clipboard access than the buggy and insecure Flash fallback that's needed for Safari?

iOS8 release completely blew any confidence I had in Apple. They broke so much in Safari and caused an immense amount of work. IIRC web workers broke after sleeping the screen. That one was a huge problem.

You are in my experience 80 % wrong ( ahead of Chrome / Firefox). I develop webapplications at my work.

The only thing that Safari is good at is memory footprint and batterly life.

An objective view: https://html5test.com/results/desktop.html

That’s not an “objective view”. It’s just one particular dude’s feature comparison chart, without any attempt to judge or explain the merits of the features involved or the quality of implementations.

It's more objective then what you wrote, because what you wrote comes down to:

Safari is better then everything and all the rest doesn't come near. The features that it copied from Chrome made Safari worse and at they don't spy on me or sell me to advertisers.

Note: Apple has iAd and does the same, it just doesn't want Google to do it.

At least i wrote some pro's for Safari... And it's a live feature tester for HTML 5 according to the W3C HTML 5 specifications, and safari lags far behind. It runs all the test cases and the best browser comes on top. The worst browser falls behind.. In this "objective" test, Safari falls short and Chrome, Opera and Firefox are much better.

So yes, it is much more objective then your opinion ;-)

you know of a better page than html5test?

please, enlighten us.

The point is that 'more features' isn't necessarily better[1], so no list of html5 feature support is going to tell you much about how 'good' a browser is.

[1] case in point: the misfeature we are discussing in this thread, which is just another addition to the big list of browser features that I have to go out of my way to disable to get a sane experience that minimises my exposure to the incompetence of web developers

More features for web applications mean a faster distance from mobile native applications.

That is (according to me) the true reason why Apple doesn't add features to Safari ;)

Is it possible you're having this experience because Safari just is ignoring a whole bunch of stuff (that makes the web-pages slow and cumbersome) because it's too outdated to understand?

Battery life it does have an advantage on, AFAIK this is widely understood and both Google and Mozilla are trying to address it (if they can, Apple does have nonpublic/undocumented APIs...). I'm surprised you find it outperforming Firefox wrt memory usage, though.

You probably ain't a web developer.

Safari is so behind even compared to IE.

Same as this project. DataTables filters out Safari for some of it's extension:


It's just business: Apple makes no money from browsing, Google does.

It is in Apple's interest that people don't browse at all, and spend their time inside apps, where Apple has a much bigger chance of getting revenue sharing.

They are deprecating the browser, on purpose.

[Edit: this doesn't mean Apple is bad, they are just a rational company; it would be weird if they weren't doing it]

> For my own browsing habits, Firefox is very sluggish, and Chrome is completely unusable: it just can’t handle the load and brings my whole computer to a crawl.

Any example of those pages that brings the computer to a crawl?

It’s not any particular page that makes Chrome die. It’s opening more than 30 at a time. (I typically have anywhere from 50–200 browser tabs open at once.)

Do you use task manager (Hotdog menu > More tools) to kill tabs that you are not currently using? Also chrome 46 looks to be getting much better[0]; although I have also noticed a sizeable improvement with 45.

[0] http://thenextweb.com/apps/2015/08/20/chrome-is-finally-gett...


Anecdotally, leaving open for long periods of time causes problems, when that tab tab that includes Flash. Since Flash is fairly prevalent among Web ads, etc., it basically happens all the time.

I'm sure there's some configuration setting or extension I could use to change this behavior. However, switching to Safari fixes it as well (and gets me improved battery life overall). I haven't really noticed any downsides to using Safari vs. Chrome.

I'm going to assume 100+ open tabs.

I mostly ignore Safari by now. I work around its worst limitations so the sites are usable, but that's it.

Safari is the new Internet Explorer.

Let's see... Comes preinstalled with OS, has small memory footprint, very fast loading, low CPU usage and shitty support for newer web tech.

Yup, all checks out.

So Safari is holding back webdev because it doesn't support an experimental technology?

Fun thing: the author of the Selection API draft works for Apple :-)


The Selection API works in Safari, what doesn't work is the clipboard API.

It is working on Safari for me.

Hardly. Different priorities. Safari on Mac is miles ahead on battery life and footprint. When I'm on a laptop, that matters way way more than any experimental feature. It's literally hours better.

I have to ask though, what mission critical ratified features do you need that Safari lacks?

Why isn't this more common?!? Are you trolling? Every script copying random stuff (read marketing messages) into my clipboard, well sign me up, thats what i have sooo wanted for sooo many years. Luckily Safari is my browser of choice.

IIRC the clipboard copy only happens if you first click so it must be user-initiated. Now I'm sure using flash there are other sneaky ways to do it. For example some sights when you select text and copy it will attach the URL of the page your are on at the end of the text which drives me crazy. If I want the URL I'll copy it, until then stay out of my way.

I actually was thinking that the graceful degrade was how it was implemented initially and was about to write it off until I got to that part. Interesting.

At this point I still don't buy that Apple is doing this to hold things back. Do you have other examples of when they've been behind on features with no clear explanation of why? It's okay if not - you said you were only casually following - but curious.

They wouldn't have very much to gain in my mind - none of their core business relies on locking in/out web development. They have an app market, and I guess you could argue they're trying to drive that, but they have implemented a lot of other features, and early extensions in many cases, that doesn't really align with them trying to hold web back.

Well, for one, local storage in private mode has been completely borked for at least for a couple of years now.

Seems we have a new IE 6

I came across an article yesterday that said this too. I don't know, I am not a Safari user, but I doubt Apple will take years to upgrade like IE6. http://nolanlawson.com/2015/06/30/safari-is-the-new-ie/

ZeroClipboard is adding support for the HTML5 clipboard API , while retaining Flash fallback for older browsers:


Yup, Safari's lack of getUserMedia() is the sole reason we have to continue using flash at my job.

What does this do that OS native clipboards don't? Serious question - are there platforms I'm unaware of where the functionality doesn't exist but a web browser does? Seems unlikely to me, but I might be wrong.

It gives you a button you can click to select a predetermined piece of text and add it to your clipboard. That's it. This is handy from a usability perspective in some circumstances.

The documentation is a bit coy about this, but the usual purpose for this sort of library is so you can modify the copied text before it hits the user's clipboard, to insert an advertisement or copyright notice. (See the 'data-clipboard-text' attribute.)

So, for evil. Safari not supporting execCommand copy and paste is a good thing for users.

(This claims to work in all major browsers except Safari, but I'm see the same fallback when I try it in Firefox, on OS X at least -- it shows the key combination in a popup instead of actually copying or cutting the text as it does in Chrome.)

I needed a simple "click to copy some data" so I made this simple function: https://gist.github.com/mdamien/a0f2bd91750a2d45c8ab

I feel like the need for a whole library here is a bit overkill if you have a "simple" usage.

Does it copy/paste image data too? My brief look at the docs doesn't seem to mention it but it would be ace if it did...

Glad to see new libraries for the new clipboard API! I was recently making a color picker website that would not use flash for copying color values (http://0xrgb.com) and I was really missing a library like this. Anyway thanks, I hope it will replace zeroclipboard very soon!

I'd love to see the ability to paste without using the keyboard too. Is that something possible/on the roadmap?

I don't think so. Ability to access information in user's system clipboard seems like a huge security and privacy issue.

execCommand paste is limited by browsers, so synthetic events don't have the content (see section 8 of http://www.w3.org/TR/clipboard-apis/). although that would increase the capabilities of web apps so people could nicely integrate custom copy/paste, it seems to be a security risk (eg you can grab the clipboard contents and paste to a hidden input field, then post to server without the user knowing).

you can plug into the paste pipeline and replace the data pasted when a user causes paste, either by clipboard or clicking on the browser menu/context menu though, just using the html5 events. You don't need a separate library for that.

In linux middle button pastes any previously highlighted text.

its awesome.

Just switched https://wakatime.com/ to this yesterday... it's so much better than ZeroClipboard!

1. ZeroClipboard has issues with Bootstrap tooltips on the copy button

2. This doesn't depend on Flash!

3. Gracefully downgrades to a "Press Ctrl+C to copy" message for Safari

The irony of telling safari users to "press control c" is ridiculous.

Safari on iOS doesn't have a control key and on OS X copy is "Command-C"

But honestly the idea that someone can't select text and copy it themselves (and thus need this helper) is a stretch of reality anyway so why am I surprised that it doesn't reflect reality in its "fallback" either..

It's not a stretch. If you have a product that "real" people use and phone number for customer support, you will quickly learn the value of a copy-to-clipboard feature.

People cannot even successfully select complete URLs at an alarming frequency.

> If you have a product that "real" people use and phone number for customer support, you will quickly learn the value of a copy-to-clipboard feature

Real people have being using regular select + copy operations on their device of choice, for literally decades.

I honestly don't understand why every web app developer assumes that their user base is full of people that just picked up a device with a browser and have never used it before.

We don't assume anything. We take calls from customers where they can't figure out how to copy and paste. We take calls where customers don't even know what a browser is, or a web page, or in some extreme cases how to select a textbox and type in it.

Just because your customers (assuming you do web dev) can figure things out doesn't mean everyones' can.

Unfortunately we've already received a lot of requests for click-to-copy in the app my company is building. I'd rather we didn't have to add it (because Flash), but we have to add it.

People wouldn't add this feature (along with the bloated library required to make it possible) to their web apps if the demand wasn't there.

Started project 13 days ago and has 4k+ GitHub Stars

"This might come in handy; better star it."

Okay, who pressed the star button? https://github.com/zenorocha/clipboard.js/issues/56

And for the truly adventurous, there's the html5 clipboard api.

Isn't the "problem" of the HTML5 clipboard API that you can only access the clipboard during clipboard events, so you can't put stuff in the clipboard on a button click, which is exactly the user-case for this library?

This is very true, though I was mostly commenting on the "Modern copy to clipboard" description.

Clipboard.js uses the HTML5 clipboard API.

The whole point of flash-based clipboard libraries are to support legacy browsers. This attempt at removing those falls flat and does not support ie8, sigh...

IE8 is holding the rest of us back. Reality is that most usage of IE8 comes from corporate users who are stuck on such IE8. We can't keep supporting legacy browsers forever. The solution that has been working is to warn the user that their browser is not officially supported, and that things will break.

One of the banks that I consult with allow users to install the corporately limited version of Chrome, it's sometimes 10 or more versions behind latest stable, but it's better than IE8.

Bootstrap, Font-Awesome, jQuery are dropping IEx because it's a burden to maintain that for a small subset of users. We should all do the same.

I personally follow Google in what I support unless the project I am working on is specifically for older browsers.

My idea is if Google who owns a huge market share of the web can drop it, it's safe to say so can I.

According to statcounter (which I'm not claiming is accurate, just the only up-to-date source I could find) as of August 2015 IE8 had a market share of 2.32%. You have to be really unlucky with your audience/service if you really need to support IE8.

Microsoft themselves aren't going to be supporting IE8 anymore after January. Let it go.

Another trick using clipboards (in Mac OS X): use pbcopy/pbpaste to copy and paste to clipboard

So modern!

Isn't any library released today, which improves on libraries from yesterday, by definition "modern"?

Whenever I hear "modern" I just picture the developer thumbing his nose at the old fuddy-duddies who don't know how to code and spew out garbage. Yeah yeah, I get it -- the older stuff sucks. But maybe I'm imagining it. If people here tell me that the word "modern" is truly free of derision, I'm open to that viewpoint.

Well, in this case it relies on the Selection API which is currently still a Working Draft - that sounds quite "modern" to me. It also eschews an older technology (Flash) in favour of newer ones, so that also seems to be a forgivable usage of the word.

I think it would be fair to describe this as a modern and quite reasonable alternative to the venerable (see what I did there?) ZeroClipboard.

Well, in this case it's being used with derision; it's deriding clipboard libraries that rely on hidden Flash players to get access to the clipboard.

Browsers support clipboard events for a long time. Except safari. Because Safari, we have to use that "flash & bloated frameworks".

Because "the people using safari" is still a thing (i dont know why)

I use Safari because Firefox and Chrome are both bloated pieces of crap. I can open 30 tabs simultaneously in Safari with minimal impact on my CPU, while Chrome locks up for close to a minute as it tries to cope. Much better smooth scrolling performance, integration with Safari on iOS, etc.

The only thing I wish Safari had that Chrome does is profiles.

I find Chrome to be a CPU hog. This may have to do with each tab running in its own process. Can this be disabled, or can processes be suspended if they are not the top tab?

I don't open a lot of tabs on Chrome because of this.

Applications are open for YC Winter 2022

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact