List of usage examples for android.webkit WebSettings setJavaScriptEnabled
public abstract void setJavaScriptEnabled(boolean flag);
From source file:android.webkit.cts.WebViewTest.java
public void testAddJavascriptInterfaceExceptions() throws Exception { WebSettings settings = mOnUiThread.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); final AtomicBoolean mJsInterfaceWasCalled = new AtomicBoolean(false) { @JavascriptInterface/* w w w . j av a 2s . c om*/ public synchronized void call() { set(true); // The main purpose of this test is to ensure an exception here does not // crash the implementation. throw new RuntimeException("Javascript Interface exception"); } }; mOnUiThread.addJavascriptInterface(mJsInterfaceWasCalled, "dummy"); mOnUiThread.loadUrlAndWaitForCompletion("about:blank"); assertFalse(mJsInterfaceWasCalled.get()); final CountDownLatch resultLatch = new CountDownLatch(1); mOnUiThread.evaluateJavascript("try {dummy.call(); 'fail'; } catch (exception) { 'pass'; } ", new ValueCallback<String>() { @Override public void onReceiveValue(String result) { assertEquals("\"pass\"", result); resultLatch.countDown(); } }); assertTrue(resultLatch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(mJsInterfaceWasCalled.get()); }
From source file:android.webkit.cts.WebViewTest.java
@UiThreadTest public void testAddJavascriptInterface() throws Exception { if (!NullWebViewUtils.isWebViewAvailable()) { return;/*from w ww . j a v a2s . c o m*/ } WebSettings settings = mWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); final class DummyJavaScriptInterface { private boolean mWasProvideResultCalled; private String mResult; private synchronized String waitForResult() { while (!mWasProvideResultCalled) { try { wait(TEST_TIMEOUT); } catch (InterruptedException e) { continue; } if (!mWasProvideResultCalled) { Assert.fail("Unexpected timeout"); } } return mResult; } public synchronized boolean wasProvideResultCalled() { return mWasProvideResultCalled; } @JavascriptInterface public synchronized void provideResult(String result) { mWasProvideResultCalled = true; mResult = result; notify(); } } final DummyJavaScriptInterface obj = new DummyJavaScriptInterface(); mWebView.addJavascriptInterface(obj, "dummy"); assertFalse(obj.wasProvideResultCalled()); startWebServer(false); String url = mWebServer.getAssetUrl(TestHtmlConstants.ADD_JAVA_SCRIPT_INTERFACE_URL); mOnUiThread.loadUrlAndWaitForCompletion(url); assertEquals("Original title", obj.waitForResult()); // Verify that only methods annotated with @JavascriptInterface are exposed // on the JavaScript interface object. mOnUiThread.evaluateJavascript("typeof dummy.provideResult", new ValueCallback<String>() { @Override public void onReceiveValue(String result) { assertEquals("\"function\"", result); } }); mOnUiThread.evaluateJavascript("typeof dummy.wasProvideResultCalled", new ValueCallback<String>() { @Override public void onReceiveValue(String result) { assertEquals("\"undefined\"", result); } }); mOnUiThread.evaluateJavascript("typeof dummy.getClass", new ValueCallback<String>() { @Override public void onReceiveValue(String result) { assertEquals("\"undefined\"", result); } }); }
From source file:com.tct.mail.ui.ConversationViewFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //TS: chao-zhang 2015-12-10 EMAIL BUGFIX_1121860 MOD_S 544 //NOTE: when infalte conversationView which is implements from WebView,webview.jar is not exist //or not found,NameNotFoundException exception thrown,and InflateException thrown in Email,BAD!!! View rootView;/*from w w w .jav a 2s . co m*/ try { rootView = inflater.inflate(R.layout.conversation_view, container, false); } catch (InflateException e) { LogUtils.e(LOG_TAG, e, "InflateException happen during inflate conversationView"); //TS: xing.zhao 2016-4-1 EMAIL BUGFIX_1892015 MOD_S if (getActivity() == null) { return null; } else { rootView = new View(getActivity().getApplicationContext()); return rootView; } //TS: xing.zhao 2016-4-1 EMAIL BUGFIX_1892015 MOD_E } //TS: chao-zhang 2015-12-10 EMAIL BUGFIX_1121860 MOD_E //TS: tao.gan 2015-09-10 EMAIL FEATURE-559891 ADD_S //Here we romve the imagebutton and then add it ,to make it show on the top level. //Because we can't add the fab button at last on the layout xml. mFabButton = (ConversationReplyFabView) rootView.findViewById(R.id.conversation_view_fab); FrameLayout framelayout = (FrameLayout) rootView.findViewById(R.id.conversation_view_framelayout); framelayout.removeView(mFabButton); framelayout.addView(mFabButton); //TS: tao.gan 2015-09-10 EMAIL FEATURE-559891 ADD_E mConversationContainer = (ConversationContainer) rootView.findViewById(R.id.conversation_container); mConversationContainer.setAccountController(this); mTopmostOverlay = (ViewGroup) mConversationContainer.findViewById(R.id.conversation_topmost_overlay); mTopmostOverlay.setOnKeyListener(this); inflateSnapHeader(mTopmostOverlay, inflater); mConversationContainer.setupSnapHeader(); setupNewMessageBar(); mProgressController = new ConversationViewProgressController(this, getHandler()); mProgressController.instantiateProgressIndicators(rootView); mWebView = (ConversationWebView) mConversationContainer.findViewById(R.id.conversation_webview); //TS: junwei-xu 2015-3-25 EMAIL BUGFIX_919767 ADD_S if (mWebView != null) { mWebView.setActivity(getActivity()); } //TS: junwei-xu 2015-3-25 EMAIL BUGFIX_919767 ADD_E //TS: tao.gan 2015-09-10 EMAIL FEATURE-559891 ADD_S mWebView.setFabButton(mFabButton); //TS: tao.gan 2015-09-10 EMAIL FEATURE-559891 ADD_E mWebView.addJavascriptInterface(mJsBridge, "mail"); // On JB or newer, we use the 'webkitAnimationStart' DOM event to signal load complete // Below JB, try to speed up initial render by having the webview do supplemental draws to // custom a software canvas. // TODO(mindyp): //PAGE READINESS SIGNAL FOR JELLYBEAN AND NEWER // Notify the app on 'webkitAnimationStart' of a simple dummy element with a simple no-op // animation that immediately runs on page load. The app uses this as a signal that the // content is loaded and ready to draw, since WebView delays firing this event until the // layers are composited and everything is ready to draw. // This signal does not seem to be reliable, so just use the old method for now. final boolean isJBOrLater = Utils.isRunningJellybeanOrLater(); final boolean isUserVisible = isUserVisible(); mWebView.setUseSoftwareLayer(!isJBOrLater); mEnableContentReadySignal = isJBOrLater && isUserVisible; mWebView.onUserVisibilityChanged(isUserVisible); mWebView.setWebViewClient(mWebViewClient); final WebChromeClient wcc = new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { if (consoleMessage.messageLevel() == ConsoleMessage.MessageLevel.ERROR) { //TS: wenggangjin 2015-01-29 EMAIL BUGFIX_-917007 MOD_S // LogUtils.wtf(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(), LogUtils.w(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(), consoleMessage.sourceId(), consoleMessage.lineNumber(), ConversationViewFragment.this); //TS: wenggangjin 2015-01-29 EMAIL BUGFIX_-917007 MOD_E } else { LogUtils.i(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(), consoleMessage.sourceId(), consoleMessage.lineNumber(), ConversationViewFragment.this); } return true; } }; mWebView.setWebChromeClient(wcc); final WebSettings settings = mWebView.getSettings(); final ScrollIndicatorsView scrollIndicators = (ScrollIndicatorsView) rootView .findViewById(R.id.scroll_indicators); scrollIndicators.setSourceView(mWebView); settings.setJavaScriptEnabled(true); ConversationViewUtils.setTextZoom(getResources(), settings); //Enable third-party cookies. b/16014255 if (Utils.isRunningLOrLater()) { CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true /* accept */); } mViewsCreated = true; mWebViewLoadedData = false; return rootView; }
From source file:com.free.searcher.MainFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup viewContainer, Bundle savedInstanceState) { super.onCreateView(inflater, viewContainer, savedInstanceState); this.activity = getActivity(); actionBar = activity.getActionBar(); View v = inflater.inflate(R.layout.main, viewContainer, false); v.setOnSystemUiVisibilityChangeListener(this); webView = (WebView) v.findViewById(R.id.webView1); statusView = (TextView) v.findViewById(R.id.statusView); if (webViewBundle != null) { webView.restoreState(webViewBundle); Log.d("onCreateView.webView.restoreState", webViewBundle + ""); } else if (currentUrl.length() > 0) { Log.d("onCreateView.locX, locY", locX + ", " + locY + ", " + currentUrl); webView.loadUrl(currentUrl);/* ww w . j av a2 s. c om*/ webView.setScrollX(locX); webView.setScrollY(locY); Log.d("currentUrl 8", currentUrl); } statusView.setText(status); Log.d("onCreateView.savedInstanceState", savedInstanceState + "vvv"); mNotificationManager = (NotificationManager) activity.getSystemService(activity.NOTIFICATION_SERVICE); webView.setFocusable(true); webView.setFocusableInTouchMode(true); webView.requestFocus(); webView.requestFocusFromTouch(); webView.getSettings().setAllowContentAccess(false); webView.getSettings().setPluginState(WebSettings.PluginState.OFF); // webView.setBackgroundColor(LIGHT_BLUE); webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webView.setBackgroundColor(getResources().getColor(R.color.lightyellow)); webView.setOnLongClickListener(this); statusView.setOnLongClickListener(this); webView.setWebViewClient(new WebViewClient() { private void jumpTo(final int xLocation, final int yLocation) { webView.postDelayed(new Runnable() { @Override public void run() { Log.d("jumpTo1.locX, locY", xLocation + ", " + yLocation + ", " + currentUrl); try { webView.scrollTo(xLocation, yLocation); webView.setScrollX(xLocation); webView.setScrollY(yLocation); // locX = 0; // locY = 0; } catch (RuntimeException e) { Log.e("error jumpTo2.locX, locY", locX + ", " + locY + ", " + currentUrl); } } }, 100); } @Override public boolean shouldOverrideUrlLoading(WebView view, final String url) { if (currentZipFileName.length() > 0 && (extractFile == null || extractFile.isClosed())) { try { extractFile = new ExtractFile(currentZipFileName, MainFragment.PRIVATE_PATH + currentZipFileName); } catch (RarException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } int ind = url.indexOf("?deleteFile="); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } String urlStatus = Util.getUrlStatus(url); final String selectedFile = urlStatus.substring(urlStatus.indexOf("?deleteFile=") + 12, urlStatus.length()); Log.d("deleteFile", "url=" + url + ", urlStatus=" + urlStatus); AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.setTitle("Delete File?"); alert.setMessage("Do you really want to delete file \"" + selectedFile + "\"?"); alert.setCancelable(true); alert.setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { locX = webView.getScrollX(); locY = webView.getScrollY(); webView.loadUrl( new File(dupTask.deleteFile(selectedFile)).toURI().toURL().toString()); } catch (IOException e) { statusView.setText(e.getMessage()); Log.d("deleteFile", e.getMessage(), e); } } }); alert.setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); return true; } ind = url.indexOf("?deleteGroup="); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } String urlStatus = Util.getUrlStatus(url); final String groupFile = urlStatus.substring(urlStatus.indexOf("?deleteGroup=") + 13, urlStatus.length()); int indexOf = groupFile.indexOf(","); final int group = Integer.parseInt(groupFile.substring(0, indexOf)); final String selectedFile = groupFile.substring(indexOf + 1); Log.d("groupFile", ",groupFile=" + groupFile + ", url=" + url + ", urlStatus=" + urlStatus); AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.setTitle("Delete Group of Files?"); alert.setMessage( "Do you really want to delete this group, except file \"" + selectedFile + "\"?"); alert.setCancelable(true); alert.setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { locX = webView.getScrollX(); locY = webView.getScrollY(); webView.postDelayed(new Runnable() { @Override public void run() { try { webView.loadUrl(new File(dupTask.deleteGroup(group, selectedFile)).toURI() .toURL().toString()); } catch (Throwable e) { statusView.setText(e.getMessage()); Log.e("Delete Group", e.getMessage(), e); Log.e("Delete Group", locX + ", " + locY + ", " + currentUrl); } } }, 0); } }); alert.setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); return true; } ind = url.indexOf("?deleteFolder="); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } String urlStatus = Util.getUrlStatus(url); final String selectedFile = urlStatus.substring(urlStatus.indexOf("?deleteFolder=") + 14, urlStatus.length()); Log.d("deleteFolder", ",deleteFolder=" + selectedFile + ", url=" + url + ", urlStatus=" + urlStatus); AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.setTitle("Delete folder?"); alert.setMessage("Do you really want to delete duplicate in folder \"" + selectedFile.substring(0, selectedFile.lastIndexOf("/")) + "\"?"); alert.setCancelable(true); alert.setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { locX = webView.getScrollX(); locY = webView.getScrollY(); webView.postDelayed(new Runnable() { @Override public void run() { try { webView.loadUrl(new File(dupTask.deleteFolder(selectedFile)).toURI().toURL() .toString()); } catch (Throwable e) { statusView.setText(e.getMessage()); Log.e("Delete folder", e.getMessage(), e); Log.e("Delete folder", locX + ", " + locY + ", " + currentUrl); } } }, 0); } }); alert.setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); return true; } ind = url.indexOf("?deleteSub="); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } String urlStatus = Util.getUrlStatus(url); final String selectedFile = urlStatus.substring(urlStatus.indexOf("?deleteSub=") + 11, urlStatus.length()); Log.d("deleteSub", ",deleteSub=" + selectedFile + ", url=" + url + ", urlStatus=" + urlStatus); AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.setTitle("Delete sub folder?"); alert.setMessage("Do you really want to delete duplicate files in sub folder of \"" + selectedFile.substring(0, selectedFile.lastIndexOf("/")) + "\"?"); alert.setCancelable(true); alert.setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { locX = webView.getScrollX(); locY = webView.getScrollY(); webView.postDelayed(new Runnable() { @Override public void run() { try { webView.loadUrl(new File(dupTask.deleteSubFolder(selectedFile)).toURI() .toURL().toString()); } catch (Throwable e) { statusView.setText(e.getMessage()); Log.e("Delete sub folder", e.getMessage(), e); Log.e("Delete sub folder", locX + ", " + locY + ", " + currentUrl); } } }, 0); } }); alert.setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); return true; } ind = url.indexOf("?viewName"); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } nameOrder = !nameOrder; locX = 0; locY = 0; Log.d("url=", url + ", viewName"); try { webView.loadUrl(new File(dupTask.genFile(dupTask.groupList, dupTask.NAME_VIEW)).toURI() .toURL().toString()); } catch (IOException e) { Log.e("viewName", e.getMessage(), e); } return true; } ind = url.indexOf("?viewGroup"); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } groupViewChanged = true; locX = 0; locY = 0; Log.d("url=", url + ", viewGroup"); try { webView.loadUrl(new File(dupTask.genFile(dupTask.groupList, dupTask.GROUP_VIEW)).toURI() .toURL().toString()); } catch (IOException e) { Log.e("viewGroup", e.getMessage(), e); } return true; } if (zextr == null) { locX = 0; locY = 0; } else { zextr = null; } if (MainActivity.popup) { final MainFragment frag = ((MainActivity) activity).addFragmentToStack(); frag.status = Util.getUrlStatus(url); frag.load = load; frag.currentSearching = currentSearching; frag.selectedFiles = selectedFiles; frag.files = files; frag.currentZipFileName = currentZipFileName; if (extractFile != null) { try { frag.extractFile = new ExtractFile(); extractFile.copyTo(frag.extractFile); } catch (RarException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } frag.home = home; // if (mSearchView != null && mSearchView.getQuery().length() > 0) { // frag.mSearchView.setQuery(mSearchView.getQuery(), false); // } view.getHandler().postDelayed(new Runnable() { @Override public void run() { frag.webTask = new WebTask(MainFragment.this); frag.webTask.init(frag.webView, url); frag.webTask.execute(); frag.statusView.setText(frag.status); } }, 100); } else { currentUrl = url; Log.d("currentUrl 19", currentUrl); status = Util.getUrlStatus(url); statusView.setText("Opening " + url + "..."); webTask = new WebTask(MainFragment.this, webView, url, status.toString()); webTask.execute(); } // setNavVisibility(false); return true; } // @Override // public WebResourceResponse shouldInterceptRequest(WebView view, String url) { // } @Override public void onPageFinished(WebView view, String url) { if (container != null) { if (showFind) { container.setVisibility(View.VISIBLE); webView.findAllAsync(findBox.getText().toString()); } else { container.setVisibility(View.INVISIBLE); } } Log.d("onPageFinished", locX + ", " + locY + ", currentUrl=" + currentUrl + ", url=" + url); setNavVisibility(false); if (!backForward) { //if (zextr != null) { // zextr = null; jumpTo(locX, locY); } else { backForward = false; } // locX = 0; // locY = 0; Log.d("onPageFinished", url); /* This call inject JavaScript into the page which just finished loading. */ // webView.loadUrl("javascript:window.HTMLOUT.processHTML(" + // "'<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');"); } }); WebSettings settings = webView.getSettings(); // webView.setWebViewClient(new WebViewClient()); // webView.setWebChromeClient(new WebChromeClient()); // webView.addJavascriptInterface(new HtmlSourceViewJavaScriptInterface(), "HTMLOUT"); settings.setMinimumFontSize(13); settings.setJavaScriptEnabled(true); settings.setDefaultTextEncodingName("UTF-8"); settings.setBuiltInZoomControls(true); // settings.setSansSerifFontFamily("Tahoma"); settings.setEnableSmoothTransition(true); return v; }