Java Code Examples for android.webkit.WebView#addJavascriptInterface()

The following examples show how to use android.webkit.WebView#addJavascriptInterface() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebDataActivity.java    From YCCustomText with Apache License 2.0 6 votes vote down vote up
public void initWebView(String data) {
        WebView mWebView = findViewById(R.id.showdiarys);
        WebSettings settings = mWebView.getSettings();

        //settings.setUseWideViewPort(true);//调整到适合webview的大小,不过尽量不要用,有些手机有问题
        settings.setLoadWithOverviewMode(true);//设置WebView是否使用预览模式加载界面。
        mWebView.setVerticalScrollBarEnabled(false);//不能垂直滑动
        mWebView.setHorizontalScrollBarEnabled(false);//不能水平滑动
        settings.setTextSize(WebSettings.TextSize.NORMAL);//通过设置WebSettings,改变HTML中文字的大小
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
        //设置WebView属性,能够执行Javascript脚本
        mWebView.getSettings().setJavaScriptEnabled(true);//设置js可用
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.addJavascriptInterface(new AndroidJavaScript(getApplication()), "android");//设置js接口
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局


/******  22222222  ***********************************************************************/
        data = "</Div><head><style>img{ width:100% !important;}</style></head>" + data;//给图片设置一个样式,宽满屏
/******  2222222222  ***********************************************************************/

        mWebView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
    }
 
Example 2
Source File: QUnitMixTest.java    From androidtestdebug with MIT License 6 votes vote down vote up
public void test通过本地资源网页执行安卓与QUnit混合测试() throws InterruptedException {
	// 找到待测应用的活动对象的引用
	Activity activity = getActivity();
	// 找到待测应用主界面上的WebView对象
       final WebView wv = (WebView)activity.findViewById(R.id.webview);
       // 注册收集测试结果的JavaScript桥接对象
       JavaScriptTestInterface jsti = new JavaScriptTestInterface();
       wv.addJavascriptInterface(jsti, "qunit");
       // 加载QUnit测试网页
       wv.loadUrl("file:///android_asset/qtest.html");
       // 等待QUnit用例执行完毕
       Thread.sleep(10000);
       // 收集QUnit测试结果
       wv.loadUrl("javascript:qunit.pushResult($('p#qunit-testresult.result').text());");
       Thread.sleep(1000);
       String value = jsti.popResult();
       // 对比QUnit结果中的统计数据与期望值是否匹配
       Assert.assertTrue(value.endsWith("1 assertions of 1 passed, 0 failed."));
}
 
Example 3
Source File: MainActivity.java    From Phantom with Apache License 2.0 6 votes vote down vote up
private void initWebView() {
    mWebView = (WebView) findViewById(R.id.webview);
    WebViewResourceHelper.addChromeResourceIfNeeded(this);
    final WebSettings settings = mWebView.getSettings();
    settings.setSupportZoom(true);
    settings.setBuiltInZoomControls(true);
    settings.setUseWideViewPort(true);
    settings.setJavaScriptEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient());
    mWebView.addJavascriptInterface(this, "android");
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }
    });
}
 
Example 4
Source File: CustomWebViewDialog.java    From GankDaily with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final View customView;
    try {
        customView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_webview, null);
        mWebView = (WebView) customView.findViewById(R.id.webview);
        mWebView.addJavascriptInterface(new WebAppInterface(customView.getContext()),"Android");
    } catch (InflateException e) {
        throw new IllegalStateException("This device does not support Web Views.");
    }
    return mPresenter.makeOkDialog(this,customView);
}
 
Example 5
Source File: PullToRefreshWebView2.java    From AndroidBase with Apache License 2.0 5 votes vote down vote up
@SuppressLint("JavascriptInterface")
@Override
protected WebView createRefreshableView(Context context, AttributeSet attrs) {
	WebView webView = super.createRefreshableView(context, attrs);

	// Need to add JS Interface so we can get the response back
	mJsCallback = new JsValueCallback();
	webView.addJavascriptInterface(mJsCallback, JS_INTERFACE_PKG);

	return webView;
}
 
Example 6
Source File: PullToRefreshWebView2.java    From PullToRefreshLibrary with Apache License 2.0 5 votes vote down vote up
@Override
protected WebView createRefreshableView(Context context, AttributeSet attrs) {
	WebView webView = super.createRefreshableView(context, attrs);

	// Need to add JS Interface so we can get the response back
	mJsCallback = new JsValueCallback();
	webView.addJavascriptInterface(mJsCallback, JS_INTERFACE_PKG);

	return webView;
}
 
Example 7
Source File: JsEngine.java    From MaterialQQLite with Apache License 2.0 5 votes vote down vote up
public JsEngine(Context context) {
	m_context = context;
	m_webView = new WebView(m_context);
	m_jsObject = new JsObject();
	
	WebSettings setting = m_webView.getSettings();
	setting.setJavaScriptEnabled(true);
	
	m_webView.addJavascriptInterface(m_jsObject, "JsObject");
}
 
Example 8
Source File: WebViewTask.java    From PicKing with Apache License 2.0 5 votes vote down vote up
public WebViewTask(Context context) {
    webView = new WebView(context);
    webView.addJavascriptInterface(new InJavaScriptLocalObj(), "get_source");
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            webView.loadUrl("javascript:window.get_source.getSource('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
        }
    });
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setBlockNetworkImage(true);
    webSettings.setUserAgentString("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36");
}
 
Example 9
Source File: MainActivity.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        //通过反射机制,让html的js调用java代码,参数二是js定义的关键字
        webView.addJavascriptInterface(new AndroidJs(),"momo");

        webView.setWebChromeClient(new WebChromeClient(){
            //webview 处理alart
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Log.d("momo","url:"+url);
                Log.d("momo","message:"+message);
                Log.d("momo","result:"+result.toString());
                AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).setTitle("JS标题").setMessage(message).create();
                dialog.show();
                //return true 自己处理(之后会有问题,再点击按钮就不会触发了)
                return true;
                //return false webview自己处理 不会有问题
//                return  false;
            }
        });

        //加载本地assets的html  注意:下面是asset不是assets
        webView.loadUrl("file:///android_asset/my.html");
    }
 
Example 10
Source File: SensorsDataAPI.java    From sa-sdk-android with Apache License 2.0 5 votes vote down vote up
@SuppressLint(value = {"SetJavaScriptEnabled", "addJavascriptInterface"})
@Override
@Deprecated
public void showUpWebView(WebView webView, JSONObject properties, boolean isSupportJellyBean, boolean enableVerify) {
    if (Build.VERSION.SDK_INT < 17 && !isSupportJellyBean) {
        SALog.d(TAG, "For applications targeted to API level JELLY_BEAN or below, this feature NOT SUPPORTED");
        return;
    }

    if (webView != null) {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new AppWebViewInterface(mContext, properties, enableVerify), "SensorsData_APP_JS_Bridge");
        SensorsDataAutoTrackHelper.addWebViewVisualInterface(webView);
    }
}
 
Example 11
Source File: SystemWebViewEngine.java    From BigDataPlatform with GNU General Public License v3.0 5 votes vote down vote up
private static void exposeJsInterface(WebView webView, CordovaBridge bridge) {
    if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)) {
        LOG.i(TAG, "Disabled addJavascriptInterface() bridge since Android version is old.");
        // Bug being that Java Strings do not get converted to JS strings automatically.
        // This isn't hard to work-around on the JS side, but it's easier to just
        // use the prompt bridge instead.
        return;
    }
    SystemExposedJsApi exposedJsApi = new SystemExposedJsApi(bridge);
    webView.addJavascriptInterface(exposedJsApi, "_cordovaNative");
}
 
Example 12
Source File: SystemWebViewEngine.java    From cordova-plugin-intent with MIT License 5 votes vote down vote up
private static void exposeJsInterface(WebView webView, CordovaBridge bridge) {
    if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)) {
        Log.i(TAG, "Disabled addJavascriptInterface() bridge since Android version is old.");
        // Bug being that Java Strings do not get converted to JS strings automatically.
        // This isn't hard to work-around on the JS side, but it's easier to just
        // use the prompt bridge instead.
        return;            
    }
    SystemExposedJsApi exposedJsApi = new SystemExposedJsApi(bridge);
    webView.addJavascriptInterface(exposedJsApi, "_cordovaNative");
}
 
Example 13
Source File: PullToRefreshWebView2.java    From FacebookNewsfeedSample-Android with Apache License 2.0 5 votes vote down vote up
@Override
protected WebView createRefreshableView(Context context, AttributeSet attrs) {
	WebView webView = super.createRefreshableView(context, attrs);

	// Need to add JS Interface so we can get the response back
	mJsCallback = new JsValueCallback();
	webView.addJavascriptInterface(mJsCallback, JS_INTERFACE_PKG);

	return webView;
}
 
Example 14
Source File: MainActivity.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webView = (WebView) findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
    webView.addJavascriptInterface(new AndrodJs(),"bevent");
    webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    //参数三:mimeType
    webView.loadDataWithBaseURL("", content, "text/html", "utf-8", null);
}
 
Example 15
Source File: PullToRefreshWebView2.java    From Alibaba-Android-Certification with MIT License 5 votes vote down vote up
@SuppressLint("JavascriptInterface")
@Override
protected WebView createRefreshableView(Context context, AttributeSet attrs) {
	WebView webView = super.createRefreshableView(context, attrs);

	// Need to add JS Interface so we can get the response back
	mJsCallback = new JsValueCallback();
	webView.addJavascriptInterface(mJsCallback, JS_INTERFACE_PKG);

	return webView;
}
 
Example 16
Source File: PullToRefreshWebView2.java    From PullToRefresh-PinnedSection-ListView with MIT License 5 votes vote down vote up
@Override
protected WebView createRefreshableView(Context context, AttributeSet attrs) {
	WebView webView = super.createRefreshableView(context, attrs);

	// Need to add JS Interface so we can get the response back
	mJsCallback = new JsValueCallback();
	webView.addJavascriptInterface(mJsCallback, JS_INTERFACE_PKG);

	return webView;
}
 
Example 17
Source File: WebViewActivity.java    From codeexamples-android with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void onCreate(Bundle icicle) {
	super.onCreate(icicle);
	setContentView(R.layout.main);
	browser = (WebView) findViewById(R.id.webkit);
	myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	browser.getSettings().setJavaScriptEnabled(true);
	browser.addJavascriptInterface(new Locater(), "locater");
	browser.loadUrl("file:///android_asset/geoweb1.html");
}
 
Example 18
Source File: Html5Activity.java    From ClassSchedule with Apache License 2.0 4 votes vote down vote up
@SuppressLint("JavascriptInterface")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web);

    mSmoothProgress = findViewById(R.id.smooth_progress);

    Bundle bundle = getIntent().getBundleExtra("bundle");
    mUrl = bundle.getString("url");
    mTitle = bundle.getString("title", "");
    mJavaScriptInterface = bundle.getSerializable("javascript");

    initBackToolbar(TextUtils.isEmpty(mTitle) ? "加载中" : mTitle);

    Log.d("Url:", mUrl);
    Log.d("mTitle:", mTitle);


    mLayout = (LinearLayout) findViewById(R.id.web_layout);


    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    mWebView = new WebView(getApplicationContext());
    mWebView.setLayoutParams(params);
    mLayout.addView(mWebView);

    WebSettings mWebSettings = mWebView.getSettings();
    mWebSettings.setSupportZoom(true);
    mWebSettings.setLoadWithOverviewMode(true);
    mWebSettings.setUseWideViewPort(true);
    mWebSettings.setDefaultTextEncodingName("utf-8");
    mWebSettings.setLoadsImagesAutomatically(true);

    //调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface
    mWebSettings.setJavaScriptEnabled(true);

    if (mJavaScriptInterface != null) {
        mWebView.addJavascriptInterface(mJavaScriptInterface, "android");
    }

    mWebView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            downloadByBrowser(url);
        }
    });

    saveData(mWebSettings);

    newWin(mWebSettings);

    mWebView.setWebChromeClient(webChromeClient);


    mWebView.setWebViewClient(webViewClient);
    mWebView.loadUrl(mUrl);
}
 
Example 19
Source File: SystemWebViewEngine.java    From keemob with MIT License 4 votes vote down vote up
@SuppressLint("AddJavascriptInterface")
private static void exposeJsInterface(WebView webView, CordovaBridge bridge) {
    SystemExposedJsApi exposedJsApi = new SystemExposedJsApi(bridge);
    webView.addJavascriptInterface(exposedJsApi, "_cordovaNative");
}
 
Example 20
Source File: SystemWebViewEngine.java    From pychat with MIT License 4 votes vote down vote up
@SuppressLint("AddJavascriptInterface")
private static void exposeJsInterface(WebView webView, CordovaBridge bridge) {
    SystemExposedJsApi exposedJsApi = new SystemExposedJsApi(bridge);
    webView.addJavascriptInterface(exposedJsApi, "_cordovaNative");
}