Clipboard on http: copy and paste work without the Clipboard API
Over plain http on a tailnet address the page is not a secure context and
navigator.clipboard is undefined, so the web engine refused every copy.
ClipboardReportingMessenger now answers clipboard calls through the
browser's legacy clipboard when the API is missing (web only, conditional
import): copy uses execCommand('copy') with a one-shot copy-event listener
(no focus or selection change); a paste key's Clipboard.getData takes the
browser's own paste event, the key reported not-handled so the browser
still fires it. A Paste button/menu says to use Ctrl+V or the https address.
Secure pages keep the engine path. Capture kit: --insecure and clipboard=.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'insecure_clipboard.dart';
|
||||
|
||||
/// The app's root messenger, for messages no screen owns.
|
||||
final GlobalKey<ScaffoldMessengerState> appScaffoldMessengerKey = GlobalKey();
|
||||
|
||||
@@ -10,10 +12,20 @@ final GlobalKey<ScaffoldMessengerState> appScaffoldMessengerKey = GlobalKey();
|
||||
/// The web reports a refused clipboard write or read (no permission, an
|
||||
/// insecure page, a browser without the clipboard API) as an error reply.
|
||||
String? clipboardFailureMessage(String method, PlatformException error) {
|
||||
if (error.code == insecureClipboardCode) return error.message;
|
||||
final detail = error.message?.trim() ?? '';
|
||||
// The engine's refusal on a page without the Clipboard API (one the
|
||||
// legacy clipboard did not answer).
|
||||
if (detail == 'Clipboard is not available in the context.') {
|
||||
return switch (method) {
|
||||
'Clipboard.setData' => insecureCopyMessage(),
|
||||
'Clipboard.getData' => insecurePasteMessage(),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
// The web's own reason ("Clipboard is not available in the context." on a
|
||||
// page that is not secure) helps; its generic "Clipboard.setData failed."
|
||||
// does not.
|
||||
final detail = error.message?.trim() ?? '';
|
||||
final why = detail.isEmpty || detail.startsWith('Clipboard.')
|
||||
? 'the browser refused access to the clipboard'
|
||||
: detail;
|
||||
@@ -40,11 +52,19 @@ bool showAppMessage(String message) {
|
||||
/// the terminal) writes through [Clipboard] on the platform channel, and
|
||||
/// most never look at the result: a refusal would otherwise only reach the
|
||||
/// console. The reply still reaches the caller unchanged.
|
||||
///
|
||||
/// With [insecure] (the web), a page without the Clipboard API copies and
|
||||
/// pastes through the browser's legacy clipboard instead ([InsecureClipboard]).
|
||||
class ClipboardReportingMessenger implements BinaryMessenger {
|
||||
ClipboardReportingMessenger(this._inner, {void Function(String)? report})
|
||||
: _report = report ?? _show;
|
||||
ClipboardReportingMessenger(
|
||||
this._inner, {
|
||||
void Function(String)? report,
|
||||
InsecureClipboard? insecure,
|
||||
}) : _report = report ?? _show,
|
||||
_insecure = insecure; // ignore: prefer_initializing_formals
|
||||
|
||||
final BinaryMessenger _inner;
|
||||
final InsecureClipboard? _insecure;
|
||||
final void Function(String message) _report;
|
||||
|
||||
static void _show(String message) => showAppMessage(message);
|
||||
@@ -53,19 +73,19 @@ class ClipboardReportingMessenger implements BinaryMessenger {
|
||||
|
||||
@override
|
||||
Future<ByteData?>? send(String channel, ByteData? message) {
|
||||
final reply = _inner.send(channel, message);
|
||||
if (reply == null ||
|
||||
channel != SystemChannels.platform.name ||
|
||||
message == null) {
|
||||
return reply;
|
||||
if (channel != SystemChannels.platform.name || message == null) {
|
||||
return _inner.send(channel, message);
|
||||
}
|
||||
final String method;
|
||||
final MethodCall call;
|
||||
try {
|
||||
method = _codec.decodeMethodCall(message).method;
|
||||
call = _codec.decodeMethodCall(message);
|
||||
} on Object {
|
||||
return reply;
|
||||
return _inner.send(channel, message);
|
||||
}
|
||||
if (!method.startsWith('Clipboard.')) return reply;
|
||||
final method = call.method;
|
||||
if (!method.startsWith('Clipboard.')) return _inner.send(channel, message);
|
||||
final reply = _insecure?.answer(call) ?? _inner.send(channel, message);
|
||||
if (reply == null) return reply;
|
||||
return reply.then((data) {
|
||||
_check(method, data);
|
||||
return data;
|
||||
@@ -95,6 +115,15 @@ class ClipboardReportingMessenger implements BinaryMessenger {
|
||||
_inner.handlePlatformMessage(channel, data, callback);
|
||||
|
||||
@override
|
||||
void setMessageHandler(String channel, MessageHandler? handler) =>
|
||||
_inner.setMessageHandler(channel, handler);
|
||||
void setMessageHandler(String channel, MessageHandler? handler) {
|
||||
final insecure = _insecure;
|
||||
_inner.setMessageHandler(
|
||||
channel,
|
||||
handler != null &&
|
||||
insecure != null &&
|
||||
channel == SystemChannels.keyEvent.name
|
||||
? insecure.keyEventHandler(handler)
|
||||
: handler,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// The browser's clipboard without the Clipboard API: on a page that is not
|
||||
/// a secure context (plain http on a non-localhost address) the browser has
|
||||
/// no `navigator.clipboard`, so Flutter's web engine refuses every
|
||||
/// `Clipboard.setData` and `Clipboard.getData`.
|
||||
abstract class InsecureClipboardHost {
|
||||
/// Whether the Clipboard API is missing, so this host must answer.
|
||||
bool get unavailable;
|
||||
|
||||
/// Writes [text] with the legacy copy command; false when the browser
|
||||
/// refused it (no user activation).
|
||||
bool copy(String text);
|
||||
|
||||
/// The text of the next browser `paste` event within [timeout] (which it
|
||||
/// consumes, so nothing else pastes it), empty for a paste with no text,
|
||||
/// or null when none came.
|
||||
Future<String?> nextPaste(Duration timeout);
|
||||
}
|
||||
|
||||
/// The error code of a clipboard reply refused because the page is not
|
||||
/// secure; its message is the whole explanation.
|
||||
const insecureClipboardCode = 'insecure_context';
|
||||
|
||||
bool _apple() =>
|
||||
defaultTargetPlatform == TargetPlatform.macOS ||
|
||||
defaultTargetPlatform == TargetPlatform.iOS;
|
||||
|
||||
/// Why a copy failed on a page that is not secure.
|
||||
String insecureCopyMessage() =>
|
||||
"Could not copy: this page isn't secure (http), so the browser blocks "
|
||||
'the clipboard here. Open the https address to copy.';
|
||||
|
||||
/// Why a paste failed on a page that is not secure, and what works instead.
|
||||
String insecurePasteMessage() {
|
||||
final key = _apple() ? 'Cmd+V' : 'Ctrl+V';
|
||||
return "Could not paste: this page isn't secure (http), so the browser "
|
||||
'blocks reading the clipboard here. Paste with $key, or open the '
|
||||
'https address.';
|
||||
}
|
||||
|
||||
/// Answers the app's clipboard calls when the Clipboard API is missing.
|
||||
///
|
||||
/// - `Clipboard.setData` copies with the legacy copy command, which the
|
||||
/// browser allows during a user activation (a key press or a click), as
|
||||
/// every copy in the app is.
|
||||
/// - `Clipboard.getData` asked for while a key event is being handled (the
|
||||
/// terminal's Ctrl+V, Shift+Insert, the desktop's injected paste key)
|
||||
/// takes the text of the browser's own `paste` event for that key: the
|
||||
/// key event is reported to the engine as not handled, so the browser
|
||||
/// still runs its paste. Asked for at any other time (a Paste button or
|
||||
/// menu item) there is no paste event to read, and the reply says to use
|
||||
/// the paste key.
|
||||
///
|
||||
/// On a secure page ([InsecureClipboardHost.unavailable] false) nothing is
|
||||
/// answered here and the engine's Clipboard API path runs unchanged.
|
||||
class InsecureClipboard {
|
||||
InsecureClipboard(
|
||||
this.host, {
|
||||
this.pasteWait = const Duration(milliseconds: 500),
|
||||
});
|
||||
|
||||
final InsecureClipboardHost host;
|
||||
|
||||
/// How long a paste key's clipboard read waits for its paste event.
|
||||
final Duration pasteWait;
|
||||
|
||||
static const _methods = JSONMethodCodec();
|
||||
static const _keys = JSONMessageCodec();
|
||||
|
||||
bool _inKeyEvent = false;
|
||||
bool _readDuringKey = false;
|
||||
|
||||
/// The reply to platform-channel [call], or null when the engine answers.
|
||||
Future<ByteData?>? answer(MethodCall call) {
|
||||
if (!host.unavailable) return null;
|
||||
switch (call.method) {
|
||||
case 'Clipboard.setData':
|
||||
final arguments = call.arguments;
|
||||
final text = arguments is Map ? arguments['text'] : null;
|
||||
if (text is! String) return null;
|
||||
// Copied now, inside the key or click that asked for it; only the
|
||||
// reply is asynchronous.
|
||||
final copied = host.copy(text);
|
||||
return Future.value(
|
||||
copied
|
||||
? _methods.encodeSuccessEnvelope(null)
|
||||
: _refused(insecureCopyMessage()),
|
||||
);
|
||||
case 'Clipboard.getData':
|
||||
final format = call.arguments;
|
||||
if (format != null && format != Clipboard.kTextPlain) return null;
|
||||
if (!_inKeyEvent) {
|
||||
return Future.value(_refused(insecurePasteMessage()));
|
||||
}
|
||||
_readDuringKey = true;
|
||||
return host
|
||||
.nextPaste(pasteWait)
|
||||
.then(
|
||||
(text) => text == null
|
||||
? _refused(insecurePasteMessage())
|
||||
: _methods.encodeSuccessEnvelope({'text': text}),
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static ByteData _refused(String message) =>
|
||||
_methods.encodeErrorEnvelope(code: insecureClipboardCode, message: message);
|
||||
|
||||
/// [handler] for the engine's key events (`flutter/keyevent`), reporting a
|
||||
/// key event whose handling read the clipboard as not handled, so the
|
||||
/// browser does not cancel the paste it is about to run.
|
||||
MessageHandler keyEventHandler(MessageHandler handler) {
|
||||
return (message) {
|
||||
if (!host.unavailable) return handler(message);
|
||||
final outer = _inKeyEvent;
|
||||
_inKeyEvent = true;
|
||||
_readDuringKey = false;
|
||||
final Future<ByteData?>? reply;
|
||||
try {
|
||||
reply = handler(message);
|
||||
} finally {
|
||||
_inKeyEvent = outer;
|
||||
}
|
||||
if (!_readDuringKey || reply == null) return reply;
|
||||
_readDuringKey = false;
|
||||
return reply.then((_) => _keys.encodeMessage({'handled': false}));
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import 'insecure_clipboard.dart';
|
||||
import 'insecure_clipboard_host_stub.dart'
|
||||
if (dart.library.js_interop) 'insecure_clipboard_host_web.dart'
|
||||
as platform;
|
||||
|
||||
/// The browser's legacy clipboard on the web; null elsewhere, where the
|
||||
/// platform's clipboard always answers.
|
||||
InsecureClipboardHost? insecureClipboardHost() =>
|
||||
platform.insecureClipboardHost();
|
||||
@@ -0,0 +1,3 @@
|
||||
import 'insecure_clipboard.dart';
|
||||
|
||||
InsecureClipboardHost? insecureClipboardHost() => null;
|
||||
@@ -0,0 +1,96 @@
|
||||
import 'dart:async';
|
||||
import 'dart:js_interop';
|
||||
import 'dart:js_interop_unsafe';
|
||||
|
||||
import 'package:web/web.dart' as web;
|
||||
|
||||
import 'insecure_clipboard.dart';
|
||||
|
||||
InsecureClipboardHost? insecureClipboardHost() => _BrowserClipboard();
|
||||
|
||||
/// The legacy clipboard of a page without the Clipboard API.
|
||||
class _BrowserClipboard implements InsecureClipboardHost {
|
||||
/// `navigator.clipboard` exists only in a secure context (and a browser
|
||||
/// new enough to have it); neither changes while the page is open.
|
||||
@override
|
||||
late final bool unavailable =
|
||||
!web.window.isSecureContext ||
|
||||
(web.window.navigator as JSObject)
|
||||
.getProperty<JSAny?>('clipboard'.toJS)
|
||||
.isUndefinedOrNull;
|
||||
|
||||
/// The copy command writes what its `copy` event puts on the event's
|
||||
/// clipboard data, so no element is focused or selected for it: the
|
||||
/// Flutter text field keeps its focus, caret and any IME composition, and
|
||||
/// a selection in it is not copied instead.
|
||||
@override
|
||||
bool copy(String text) {
|
||||
var written = false;
|
||||
void onCopy(web.Event event) {
|
||||
final data = (event as web.ClipboardEvent).clipboardData;
|
||||
if (data == null) return;
|
||||
data.setData('text/plain', text);
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
written = true;
|
||||
}
|
||||
|
||||
final listener = onCopy.toJS;
|
||||
web.window.addEventListener(
|
||||
'copy',
|
||||
listener,
|
||||
web.AddEventListenerOptions(capture: true),
|
||||
);
|
||||
try {
|
||||
// False (or no copy event) without a user activation.
|
||||
return web.document.execCommand('copy') && written;
|
||||
} on Object {
|
||||
return false;
|
||||
} finally {
|
||||
web.window.removeEventListener(
|
||||
'copy',
|
||||
listener,
|
||||
web.EventListenerOptions(capture: true),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Listens on the window in the capture phase, ahead of the composer's
|
||||
/// document listener and the focused element's own insertion.
|
||||
@override
|
||||
Future<String?> nextPaste(Duration timeout) {
|
||||
final result = Completer<String?>();
|
||||
late final JSFunction listener;
|
||||
Timer? timer;
|
||||
void finish(String? text) {
|
||||
if (result.isCompleted) return;
|
||||
timer?.cancel();
|
||||
web.window.removeEventListener(
|
||||
'paste',
|
||||
listener,
|
||||
web.EventListenerOptions(capture: true),
|
||||
);
|
||||
result.complete(text);
|
||||
}
|
||||
|
||||
void onPaste(web.Event event) {
|
||||
final data = (event as web.ClipboardEvent).clipboardData;
|
||||
final text = data?.getData('text/plain') ?? '';
|
||||
if (text.isNotEmpty) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
}
|
||||
// A paste with no text (files) is left to the page's other listeners.
|
||||
finish(text);
|
||||
}
|
||||
|
||||
listener = onPaste.toJS;
|
||||
web.window.addEventListener(
|
||||
'paste',
|
||||
listener,
|
||||
web.AddEventListenerOptions(capture: true),
|
||||
);
|
||||
timer = Timer(timeout, () => finish(null));
|
||||
return result.future;
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,12 @@ import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../core/keyboard/key_modifier_sync.dart';
|
||||
import 'clipboard_failures.dart';
|
||||
import 'insecure_clipboard.dart';
|
||||
import 'insecure_clipboard_host.dart';
|
||||
|
||||
/// The app's binding: Flutter's, with clipboard failures reported
|
||||
/// ([ClipboardReportingMessenger]) and, on the web, key events carrying the
|
||||
/// ([ClipboardReportingMessenger]), the browser's legacy clipboard on a page
|
||||
/// without the Clipboard API ([InsecureClipboard]) and, on the web, key events carrying the
|
||||
/// modifiers their browser events hold ([KeyModifierSync]).
|
||||
///
|
||||
/// An entry point calls [ensureInitialized] before anything else creates a
|
||||
@@ -33,6 +36,11 @@ class PipelinesBinding extends WidgetsFlutterBinding {
|
||||
}
|
||||
|
||||
@override
|
||||
BinaryMessenger createBinaryMessenger() =>
|
||||
ClipboardReportingMessenger(super.createBinaryMessenger());
|
||||
BinaryMessenger createBinaryMessenger() {
|
||||
final host = insecureClipboardHost();
|
||||
return ClipboardReportingMessenger(
|
||||
super.createBinaryMessenger(),
|
||||
insecure: host == null ? null : InsecureClipboard(host),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user