Android WebView Image Viewer Demo
Preview
Topic
This demo focus on how to get images information from android WebView, and by click any image, we can launch an activity to display all those images and provide zoom gesture supported.
Code Snippet
* inject WebView and get images information after WebView on page load finished
private addImageListener() {
//in some case, src of an img tag might be base64 string but no an url
//we can get image url by data-src if exists
( mWebView)
mWebViewloadUrl(javascript:(function(){
var objs = document.getElementsByTagName(img);
for(var i=0;i<objs.length;i++)
window.imageListener.addImage(objs[i].src, objs[i].dataset.src);
objs[i].onclick=function()
window.imageListener.openImage(this.src, this.dataset.src);
);
}
* images information getter listener
public class JavascriptInterface {
//get image information
@androidwebkitJavascriptInterface
public addImage(String , String dataSrc) {
( mLists) {
String url ;
(TextUtilsisEmpty(dataSrc) (dataSrcstartsWith(http:) dataSrcstartsWith(https:))) {
url dataSrc;
} (TextUtilsisEmpty(src) (srcstartsWith(http:) srcstartsWith(https:))) {
url src;
}
(TextUtilsisEmpty(url)
( MainActivityurl MainActivityurlcontains(url)))
mListsadd(url);
}
}
//click image action
@androidwebkitJavascriptInterface
public openImage(String , String dataSrc) {
( mLists url (mListscontains(url) mListscontains(dataSrc))) {
position mListsindexOf(url) mListsindexOf(dataSrc) mListsindexOf(url);
( position) return;
Bundle bundle Bundle();
bundleputStringArrayList(ImagesShowActivityKEY_URLS, mLists);
bundleputInt(ImagesShowActivityKEY_INDEX, position);
Intent intent Intent(MainActivity, ImagesShowActivityclass);
intentputExtras(bundle);
startActivity(intent);
}
}
}License
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
[2]