在Android Java应用中执行JavaScript操作chess.com的Play按钮时遭遇Permissions-Policy头错误,寻求替代实现方案
Hey there! Let's break this down step by step:
First, let's address that error message you saw:
Error with Permissions-Policy header: Unrecognized feature: 'interest-cohort'
Don't stress about this at all—it's just a minor HTTP header misconfiguration on chess.com's end, and it has zero impact on your JavaScript code's ability to find and click the Play button. You can safely ignore it entirely.
Your original approach using document.body.innerHTML.replace() is overcomplicated and problematic: rewriting the entire body's HTML will destroy all existing event listeners on the page, cause unnecessary re-renders, and isn't needed just to click a button. We can directly target the existing button and trigger its click event without modifying any page content.
Here are several reliable methods to do this:
Method 1: Use getElementsByClassName (Since You Tried This Earlier)
getElementsByClassName returns a collection of elements, so we'll grab the first matching element (assuming the Play button is the only one with that full set of classes):
// Get the first button matching all specified classes const playButton = document.getElementsByClassName('ui_v5-button-component ui_v5-button-primary ui_v5-button-large ui_v5-button-full')[0]; // Only attempt to click if we found the button if (playButton) { playButton.click(); } else { console.log("Play button not found—double-check the class names!"); }
Method 2: Use querySelector (Cleaner & More Flexible)
querySelector lets you use CSS-style selectors, which is a more concise way to target elements:
// Target the button using a combined class selector const playButton = document.querySelector('button.ui_v5-button-component.ui_v5-button-primary.ui_v5-button-large.ui_v5-button-full'); if (playButton) { playButton.click(); } else { console.log("Play button not found"); }
Method 3: Target by Button Text (Fallback if Classes Change)
If chess.com ever updates their button's class names, you can fall back to searching for the button by its text content (just account for extra spaces):
// Loop through all buttons to find the one with "Play" text document.querySelectorAll('button').forEach(button => { if (button.textContent.trim() === 'Play') { button.click(); } });
A quick note for your Android app: when running this code via a WebView, make sure:
- JavaScript is enabled with
webView.getSettings().setJavaScriptEnabled(true); - You execute the code after the page has fully loaded—use the
WebViewClient'sonPageFinishedcallback to callwebView.evaluateJavascript(yourJsCode, null);
内容的提问来源于stack exchange,提问作者The Amateur Coder

