/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IClipboardService } from '../../../../vs/platform/clipboard/common/clipboardService'; import { $ } from '../../../../vs/base/browser/dom'; export class BrowserClipboardService implements IClipboardService { declare readonly _serviceBrand: undefined; private readonly mapTextToType = new Map(); // unsupported in web (only in-memory) async writeText(text: string, type?: string): Promise { // With type: only in-memory is supported if (type) { this.mapTextToType.set(type, text); return; } // Guard access to navigator.clipboard with try/catch // as we have seen DOMExceptions in certain browsers // due to security policies. try { return await navigator.clipboard.writeText(text); } catch (error) { console.error(error); } // Fallback to textarea and execCommand solution const activeElement = document.activeElement; const textArea: HTMLTextAreaElement = document.body.appendChild( $('textarea', { 'aria-hidden': true }) ); textArea.style.height = '1px'; textArea.style.width = '1px'; textArea.style.position = 'absolute'; textArea.value = text; textArea.focus(); textArea.select(); document.execCommand('copy'); if (activeElement instanceof HTMLElement) { activeElement.focus(); } document.body.removeChild(textArea); return; } async readText(type?: string): Promise { // With type: only in-memory is supported if (type) { return this.mapTextToType.get(type) || ''; } // Guard access to navigator.clipboard with try/catch // as we have seen DOMExceptions in certain browsers // due to security policies. try { return await navigator.clipboard.readText(); } catch (error) { console.error(error); return ''; } } private findText = ''; // unsupported in web (only in-memory) async readFindText(): Promise { return this.findText; } async writeFindText(text: string): Promise { this.findText = text; } }