diff --git a/src/librustdoc/html/static/js/src-script.js b/src/librustdoc/html/static/js/src-script.js
index b9ab6e85603bc..2a31424c4cef5 100644
--- a/src/librustdoc/html/static/js/src-script.js
+++ b/src/librustdoc/html/static/js/src-script.js
@@ -206,6 +206,31 @@ const handleSrcHighlight = (function() {
};
}());
+// This section is a bugfix for firefox: when copying text with `user-select: none`, it adds
+// extra backline characters.
+//
+// Rustdoc issue: Workaround for https://github.com/rust-lang/rust/issues/141464
+// Firefox issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1273836
+(function() {
+ document.body.addEventListener("copy", event => {
+ let target = event.target;
+ let isInsideCode = false;
+ while (target !== document.body) {
+ if (target.tagName === "CODE") {
+ isInsideCode = true;
+ break;
+ }
+ target = target.parentElement;
+ }
+ if (!isInsideCode) {
+ return;
+ }
+ const selection = document.getSelection();
+ nonnull(event.clipboardData).setData("text/plain", selection.toString());
+ event.preventDefault();
+ });
+}());
+
window.addEventListener("hashchange", highlightSrcLines);
onEachLazy(document.querySelectorAll("a[data-nosnippet]"), el => {