You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native中获取谷歌搜索栏的输入文本?实现类键盘记录器的全局按键监听功能可行性探讨

Great question! Let’s break this down into two clear parts since you’ve got two distinct goals here:

1. Capturing Input from a Google Search Bar in React Native

This depends on whether you’re building a custom search bar (styled like Google’s) or embedding the actual Google search page via a WebView:

If you’re building your own search component in React Native, this is straightforward with the built-in TextInput component. You can capture every key press and real-time input without needing a custom keyboard:

import { TextInput, View } from 'react-native';

export default function GoogleSearchBar() {
  return (
    <View>
      <TextInput
        placeholder="Search Google"
        style={{
          borderWidth: 1,
          borderColor: '#ddd',
          borderRadius: 24,
          padding: 12,
          fontSize: 16,
        }}
        // Capture real-time input text
        onChangeText={(currentText) => {
          console.log('Current search input:', currentText);
          // Use this text for your logic (e.g., auto-suggestions)
        }}
        // Capture every individual key press
        onKeyPress={(event) => {
          console.log('Pressed key:', event.nativeEvent.key);
          // Log or process each key stroke here
        }}
      />
    </View>
  );
}

Case 2: Embedded Google Search Page (WebView)

If you’re loading the actual Google search page in a WebView, you’ll need to inject JavaScript into the WebView to listen to the search input field and send data back to your React Native code:

import { WebView } from 'react-native-webview';

export default function EmbeddedGoogleSearch() {
  // JavaScript to inject into the Google page
  const injectSearchListener = `
    // Target Google's search input field
    const searchInput = document.querySelector('input[name="q"]');
    if (searchInput) {
      // Listen for every key press
      searchInput.addEventListener('keydown', (e) => {
        window.ReactNativeWebView.postMessage(JSON.stringify({
          pressedKey: e.key,
          currentInputValue: searchInput.value
        }));
      });
      // Optional: Listen for input changes (includes paste/auto-fill)
      searchInput.addEventListener('input', (e) => {
        window.ReactNativeWebView.postMessage(JSON.stringify({
          currentInputValue: e.target.value
        }));
      });
    }
  `;

  return (
    <WebView
      source={{ uri: 'https://www.google.com' }}
      injectedJavaScript={injectSearchListener}
      onMessage={(event) => {
        const data = JSON.parse(event.nativeEvent.data);
        console.log('Received from Google search:', data);
        // Process the key press or input value in your RN app
      }}
    />
  );
}
2. Global Key Capture (Like a Keylogger) Across the Entire App

This is trickier, but possible with native code integration—you can’t do this purely with React Native’s JavaScript layer, since JS runs in a sandbox and doesn’t have access to system-level keyboard events.

How to Implement It:

You’ll need to build a custom native module (or use existing third-party libraries) to listen for global key events on iOS and Android, then pass those events back to your React Native code.

Example Approach (Android):

Use a native module to listen to KeyEvents and emit events to RN:

// Android Native Module snippet (Java)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
  WritableMap params = Arguments.createMap();
  params.putInt("keyCode", keyCode);
  params.putString("keyLabel", event.getDisplayLabel().toString());
  // Send event to React Native
  sendEvent(getReactApplicationContext(), "globalKeyPress", params);
  return super.onKeyDown(keyCode, event);
}

Then in your React Native code, listen for the event:

import { NativeEventEmitter, NativeModules, useEffect } from 'react-native';

const { GlobalKeyListenerModule } = NativeModules;
const keyEmitter = new NativeEventEmitter(GlobalKeyListenerModule);

export default function GlobalKeyCapture() {
  useEffect(() => {
    const subscription = keyEmitter.addListener(
      'globalKeyPress',
      (event) => {
        console.log('Global key pressed:', event.keyLabel);
        // Log or process every key press across the app
      }
    );
    // Clean up subscription on unmount
    return () => subscription.remove();
  }, []);

  return null; // Or your app UI
}

Important Note:

Global key capture raises serious privacy concerns. App Stores (Apple App Store, Google Play) will likely reject your app unless you have a legitimate, user-facing use case (e.g., accessibility tools). Make sure you comply with platform guidelines and disclose this functionality clearly to users.


内容的提问来源于stack exchange,提问作者Shahriar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:17:39