admin管理员组

文章数量:1306862

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.

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.

Share Improve this question asked Feb 16, 2019 at 22:25 GIVGIV 4253 gold badges9 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

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 pare 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)
}

本文标签: javascriptReact NativeListener for change in clipboardStack Overflow