Android WebView中动态替换HTML元素:将Bing图标改为Google图标
Android WebView替换Bing图标为Google图标问题
我打开了链接https://www.bing.com/search?q=кму,需要将页面中的Bing图标替换为Google图标。我在override fun onPageFinished(view: WebView, url: String)方法中尝试了两种方案,但均未成功,请问如何正确实现?
原有尝试的两种方案
方案一
if (url == "https://www.bing.com/search?q=") { view.evaluateJavascript( ("\n"+ "windows.addEventListener(load, (event) => {\n" + " let \"style\" = document.head.appendChild(document.createElement(style));\n" + " style.innerHTML =\" .b_logo:after\" {content:url(https://www.google.ru/images/branding/googlelogo/2x/googlelogo_light_color_92x30dp.png);\n" + " };\n"+ "!important;\n"+ "});"), null ) }
方案二
view.loadDataWithBaseURL("baseURL", "htmlString", "text/html", "UTF-8", null) val htmlString = "<html><body><.b_logo:after='https://www.bing.com/rp/tfpoqzYv42r7UjQvzw0PVIoT2nY.png'></body></html>" val newHTMLString = htmlString.replace("<.b_logo:after=\"'https://www.bing.com/rp/tfpoqzYv42r7UjQvzw0PVIoT2nY.png'>", "<.b_logo:after='https://www.google.ru/images/branding/googlelogo/2x/googlelogo_light_color_92x30dp.png'>") view.loadDataWithBaseURL("baseURL", newHTMLString, "text/html", "UTF-8", null)
原有方案的问题分析
方案一的错误点
- URL判断失效:实际加载的URL包含查询参数
?q=кму,但代码中判断的是无参数的https://www.bing.com/search?q=,条件永远不成立。 - JavaScript语法错误:
windows拼写错误,应为window;- 创建style元素时,参数需为字符串
'style',而非未定义的变量style; - CSS语法混乱:
.b_logo:after的大括号位置错误,!important未正确放置在属性值后,引号转义逻辑错误; onPageFinished触发时页面已加载完成,无需再监听load事件。
方案二的错误点
- HTML结构完全不符:
htmlString是自定义的错误HTML片段,和真实Bing页面结构完全不匹配,替换操作无效; - 错误使用API:
loadDataWithBaseURL会加载新的空白页面,而非修改当前已加载的Bing页面内容。
正确实现方案
1. 初始化WebView时启用JavaScript
首先确保WebView允许执行JavaScript,否则无法修改页面DOM:
webView.settings.javaScriptEnabled = true // 可选:若Google图标存在跨域加载问题,开启跨域访问权限 webView.settings.allowUniversalAccessFromFileURLs = true
2. 在onPageFinished中执行正确的修改脚本
修改onPageFinished方法,匹配正确的URL并执行JavaScript替换图标:
override fun onPageFinished(view: WebView, url: String) { super.onPageFinished(view, url) // 匹配所有Bing搜索页URL,避免精确匹配失效 if (url.startsWith("https://www.bing.com/search")) { val jsCode = """ // 定位Bing图标元素(类名可能随页面更新变化,需自行验证) const bingLogo = document.querySelector('.b_logo'); if (bingLogo) { // 替换元素背景图为Google图标 bingLogo.style.backgroundImage = 'url(https://www.google.ru/images/branding/googlelogo/2x/googlelogo_light_color_92x30dp.png)'; // 清空伪元素:after的内容(如果原图标通过伪元素实现) const style = document.createElement('style'); style.textContent = ` .b_logo:after { content: '' !important; } `; document.head.appendChild(style); } """.trimIndent() view.evaluateJavascript(jsCode, null) } }
补充说明
- 页面元素的类名可能随Bing页面更新改变,建议通过Chrome开发者工具查看当前页面的图标元素结构,调整
querySelector的选择器; - 如果原图标是
<img>标签,可直接修改其src属性:bingLogo.src = '谷歌图标地址'。
内容的提问来源于stack exchange,提问作者Melast2
相关产品推荐
相关产品推荐

