Copy string var to clipboard in browser

#1

Is there a simple way to copy a string var to the clipboard in an ionic browser app.

I think the native clipboard plugin wont work.

In the doc they say

The Clipboard plugin provides Clipboard management for Cordova/PhoneGap that supports iOS, Android, and Windows Phone 8.

But not Windows.

#2

There is a PR that adds Windows support to the ancient base plugin that should also be able to be applied on this plugin: https://github.com/VersoSolutions/CordovaClipboard/pull/22 Fork it, apply the PR yourself, install that plugin instead of the ihadeed one. (And if it works create a PR for the ihadeed plugin with the implementation so it can be added by default).

#3

Should it be so easy?

Sorry I’m a beginner in ionic and this would be the first time i use a
cordova plugin.

I think it is a long way for me to get the skills to change a cordova
plugin.

:relieved:

#4

I recommend this post on medium if you don’t want to use the cordova plugin.

#5

Thank you for your replay. I would try clipboardjs.

I think I have to use the ordova plugin when my app run on mobile and clipboardjs when it runs on Windows as pwa.

I found this solution at stackoverflow. It wroks for me too without an external libary.

copyTextToClipboard(sourceCode) {
	var textArea = document.createElement("textarea");

	textArea.style.position = 'fixed';
	textArea.style.top = "0";
	textArea.style.left = "0";
	textArea.style.width = '2em';
	textArea.style.height = '2em';
	textArea.style.padding = "0";
	textArea.style.border = 'none';
	textArea.style.outline = 'none';
	textArea.style.boxShadow = 'none';
	textArea.style.background = 'transparent';
	switch (sourceCode){
	  case "providerSource":
	  textArea.value = this.providerSource;
	  break;
	  case "pageSource":
	  textArea.value = this.providerSource;
	  break;
	}
	document.body.appendChild(textArea);
	textArea.select();
	try {
	  var successful = document.execCommand('copy');
	  var msg = successful ? 'successful' : 'unsuccessful';
	  console.log('Copying text command was ' + msg);
	  let toast = this.toastCtrl.create({
		message: 'Copy to clipboard succesfully',
		duration: 1000
	  });
	  toast.present();
	} catch (err) {
	  console.log('Oops, unable to copy');
	}
	document.body.removeChild(textArea);
  }
1 Like
#6

I think direct DOM manipulation, as suggested in the previous post, is best avoided in Angular apps.

#7

Is it possible to add a textarea perhaps in the footer and make it invisible? Than I do not have to add and remove it all the time :slight_smile: