Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Listener for change in clipboard

Is there a way to add a listener for a change in clipboard data in React Native? Basically depending on whether the user has copied something in their clipboard, regardless of whether inside the app or with the app in the background, I want to perform some methods.

like image 774
GIV Avatar asked Jan 26 '23 17:01

GIV


1 Answers

React native does not provide you with a way to listen for such events, but you have two approaches: one that will partially work but is extremely simple and one that will be written as it should and work as it should as well, but requires a lot more effort as well.

You might create a timer with setInterval that would call Clipboard.getString() (just remember that it is async, so you should either wrap it with await or use .then(...)) and compare it with the value it received from the previous call. If the values differ, the user copied something. This method won't work if your app is in background - for that, you should substitute setInterval with a background service like this library. Moreover, it won't capture a copy if the value is the same, e.g. if the user first copied the text "sample" and then did it again, it won't detect it as the strings are the same.

The solution you should probably choose is to create a native module that would implement a native listener for iOS and for Android, separately. On Android you can bind to the ClipboardManager's OnPrimaryClipChangedListener, like that:

void setupListener(){
    final ClipboardManager clipboardMgr = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);

    clipboardMgr.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
        public void onPrimaryClipChanged() {
            String contents = clipboardMgr.getText().toString();
            // do something with it, e.g. emit an event to JS
        }
    });
}

And on iOS you can make use of UIPasteboard's UIPastedboardChangedNotification, like that:

func listener(sender: NSNotification){
    // do something
}

func setupListener(){
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("listener:"), name: UIPasteboardChangedNotification, object: nil)
}
like image 194
artus9033 Avatar answered Jan 29 '23 07:01

artus9033