I’m working on an Android project that needs to automate tasks on a website using websockets. Right now, I’m using WebView with a JS-Java interface, but it’s clunky and not ideal for background operations.
The website’s JavaScript is heavily obfuscated, making it tough to figure out the websocket API (Chrome debugger just shows ‘Binary OPCode 2’ in Frames). I can’t simply use GET/POST requests in Java.
Here’s a simplified example of what I’m dealing with:
WebView webView = new WebView(context);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:connectWebSocket();");
}
});
webView.loadUrl("https://example.com");
Is there a better way to handle this? Are there any headless browser solutions for Android that support websockets? I’m looking for something more efficient and suitable for background tasks. Any suggestions would be appreciated!
I’ve faced similar challenges with websocket automation on Android. Have you looked into using Selenium for Android? It’s not a perfect solution, but it’s been my go-to for headless browsing on mobile platforms.
Selenium can handle complex JavaScript and websockets, which sounds like what you need. You’ll need to set up an Android WebDriver, but once that’s done, you can automate pretty much anything.
One caveat: it can be resource-intensive, so you’ll need to optimize for background operations. I’ve had success running it in a foreground service with a notification to keep it alive.
Also, consider using Chrome DevTools Protocol (CDP) if you need more direct control over the websocket communication. It’s a bit more complex to set up, but gives you granular control over browser interactions.
have u considered using puppeteer for android? it’s a headless browser that supports websockets. might be worth checking out. i’ve used it for similar stuff and it worked pretty well. just make sure ur app has the right permissions for background tasks.
Have you considered using jsoup with OkHttp for websocket handling? It’s a lightweight solution that works well for background tasks on Android. I’ve used this combo in several projects to parse and interact with complex web content without the overhead of a full browser.
To handle the obfuscated JavaScript, you might need to reverse engineer the websocket calls. Use Charles Proxy or Fiddler to intercept and analyze the traffic between the app and the server. This can help you understand the websocket protocol and implement it directly in your Java code.
If you absolutely need browser capabilities, PhantomJS might be an option, though it’s no longer actively maintained. Alternatively, you could explore running a minimal Chromium instance using the Android NDK, but that’s quite complex and might be overkill for your needs.