我想替换的是 <image src="xxxx" />的地址
时间: 2023-10-06 12:10:57 浏览: 148
如果你想替换的是 `<img>` 标签中的 `src` 属性,那么你需要修改 JavaScript 代码中的正则表达式,以匹配 `<img>` 标签的 `src` 属性。下面是修改后的示例代码:
```java
public class MyWebViewClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String javascript = "javascript:(function() {"
+ "var imgs = document.getElementsByTagName('img');"
+ "for (var i = 0; i < imgs.length; i++) {"
+ "var img = imgs[i];"
+ "var url = img.getAttribute('src');"
+ "if (url.startsWith('http')) {"
+ "var xhr = new XMLHttpRequest();"
+ "xhr.open('GET', url, true);"
+ "xhr.responseType = 'arraybuffer';"
+ "xhr.onload = function() {"
+ "if (xhr.status === 200) {"
+ "var uInt8Array = new Uint8Array(xhr.response);"
+ "var i = uInt8Array.length;"
+ "var binaryString = new Array(i);"
+ "while (i--) {"
+ "binaryString[i] = String.fromCharCode(uInt8Array[i]);"
+ "}"
+ "var data = binaryString.join('');"
+ "var base64 = window.btoa(data);"
+ "img.setAttribute('src', 'data:image/png;base64,' + base64);"
+ "}"
+ "};"
+ "xhr.send();"
+ "}"
+ "}"
+ "})()";
view.loadUrl(javascript);
}
}
```
这段代码中,我们使用 `img.getAttribute('src')` 来获取 `<img>` 标签的 `src` 属性,然后将其替换为 Base64 编码字符串。同样,你需要将图片的本地路径替换为对应的路径。
阅读全文