React Native - Listener for change in clipboard

前端 未结 1 816
醉酒成梦
醉酒成梦 2021-02-06 16:29

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 w

相关标签:
1条回答
  • 2021-02-06 16:52

    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)
    }
    
    0 讨论(0)
提交回复
热议问题