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 badges1 Answer
Reset to default 10React 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
版权声明:本文标题:javascript - React Native - Listener for change in clipboard - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741826026a2399645.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论