B4A Library WebViewSettings

Hi all.

Here's a new library that makes it easy to set and get various WebView WebSettings.

Note that the official documentation for many of these settings is rather brief, sometimes vague or virtually non-existent!

Here is an alphabetical list of all methods with a short description.
I've implemented methods for many of the available settings but NOT all available settings.
If anyone has a particular need for a setting to be added please post a request in this thread.

WebViewSettings
Version:
1.31
  • WebViewSettings
    Methods:
    • getAllowFileAccess (webView1 As WebView) As Boolean
      Returns true if this WebView supports file access.
    • getCacheMode (webView1 As WebView) As String
      Return the current setting for overriding the cache mode.
      Possible return values are: "LOAD_CACHE_ELSE_NETWORK", "LOAD_CACHE_ONLY", "LOAD_DEFAULT", "LOAD_NO_CACHE" and "LOAD_NORMAL"
    • getCursiveFontFamily (webView1 As WebView) As String
      Get the cursive font family name. The default is "cursive".
      Returns the cursive font family name as a string.
    • getDOMStorageEnabled (webView1 As WebView) As Boolean
      Returns whether the DOM storage API is enabled.
    • getDatabasePath (webView1 As WebView) As String
      Returns the location where the database storage API databases are saved.
    • getDefaultFixedFontSize (webView1 As WebView) As Int
      Get the default fixed font size. The default is 16.
      Returns a non-negative integer between 1 and 72.
    • getDefaultFontSize (webView1 As WebView) As Int
      Get the default font size. The default is 16.
      Returns a non-negative integer between 1 and 72.
    • getDefaultTextEncodingName (webView1 As WebView) As String
      Get the default text encoding name. The default is "Latin-1".
      Returns the default text encoding name as a string.
    • getDefaultZoom (webView1 As WebView) As String
      Get the default zoom density of the page.
      Possible return values are: "CLOSE", "FAR" and "MEDIUM"
    • getDisplayZoomControls (webView1 As WebView) As Boolean
      Returns true if the on screen zoom buttons are displayed.
      Only supported on Android API level 11 and later.
    • getJavaScriptCanOpenWindowsAutomatically (webView1 As WebView) As Boolean
      Get if javascript can open windows automatically. The default is false.
      Returns true if javascript can open windows automatically during window.open().
    • getLightTouchEnabled (webView1 As WebView) As Boolean
      Returns true if light touches are enabled.
    • getLoadWithOverviewMode (webView1 As WebView) As Boolean
      Returns true if this WebView loads page with overview mode.
    • getLoadsImagesAutomatically (webView1 As WebView) As Boolean
      Return true if the WebView will load image resources automatically. The default is true.
    • getMinimumFontSize (webView1 As WebView) As Int
      Get the minimum font size. The default is 8.
      Returns a non-negative integer between 1 and 72.
    • getPluginState (webView1 As WebView) As String
      Get the current plugin state.
      Possible return values are: "OFF", "ON" and "ON_DEMAND"
    • getSaveFormData (webView1 As WebView) As Boolean
      Get whether the WebView is saving form data and displaying prior entries/autofill.
    • getSavePassword (webView1 As WebView) As Boolean
      Get whether the WebView is saving passwords.
    • getUseWideViewPort (webView1 As WebView) As Boolean
      Returns true if the WebView is using a wide viewport.
    • getUserAgentString (webView1 As WebView) As String
      Get the WebView's user-agent string.
    • setAllowFileAccess (webView1 As WebView, allow As Boolean)
      Enable or disable file access within WebView. File access is enabled by default.
      Note that this enables or disables file system access only.
      Assets and resources are still accessible using file:///android_asset
    • setAppCacheEnabled (webView1 As WebView, flag As Boolean)
      Tell the WebView to enable Application Caches API.
    • setAppCacheMaxSize (webView1 As WebView, appCacheMaxSize As Long)
      Set the maximum size for the Application Caches content.
      appCacheMaxSize - The cache size in bytes.
    • setAppCachePath (webView1 As WebView, appCachePath As String)
      Set a custom path to the Application Caches files.
      The client must ensure it exists before this call.
      appCachePath - String path to the directory containing Application Caches files. The appCache path can be the empty string but should not be null.
    • setCacheMode (webView1 As WebView, cacheMode As String)
      Override the way the cache is used. The way the cache is used is based on the navigation option.
      For a normal page load, the cache is checked and content is re-validated as needed.
      When navigating back, content is not revalidated, instead the content is just pulled from the cache.
      This function allows the client to override this behavior.
      cacheMode - Possible values are: "LOAD_CACHE_ELSE_NETWORK", "LOAD_CACHE_ONLY", "LOAD_DEFAULT", "LOAD_NO_CACHE" and "LOAD_NORMAL"
    • setCursiveFontFamily (webView1 As WebView, font As String)
      Set the cursive font family name.
      font - A font family name.
    • setDOMStorageEnabled (webView1 As WebView, Enabled As Boolean)
      Set whether the DOM storage API is enabled.
    • setDatabaseEnabled (webView1 As WebView, enabled As Boolean)
      Set whether the database storage API is enabled.
    • setDatabasePath (webView1 As WebView, path As String)
      Sets the location where the database storage API databases are saved.
      If path is an empty String "" then a default path will be set.
    • setDefaultFixedFontSize (webView1 As WebView, size As Int)
      Set the default fixed font size.
      size - A non-negative integer between 1 and 72.
    • setDefaultFontSize (webView1 As WebView, size As Int)
      Set the default font size.
      size - A non-negative integer between 1 and 72.
    • setDefaultTextEncodingName (webView1 As WebView, encoding As String)
      Set the default text encoding name to use when decoding html pages.
      The default is "Latin-1".
    • setDefaultZoom (webView1 As WebView, density As String)
      Set the default zoom density of the page.
      density - Possible values are: "CLOSE", "FAR" and "MEDIUM".
    • setDisplayZoomControls (webView1 As WebView, Enabled As Boolean)
      Sets whether the on screen zoom buttons are displayed.
      A combination of built in zoom controls enabled and on screen zoom controls disabled allows for pinch to zoom to work without the on screen controls.
      Only supported on Android API level 11 and later.
    • setGeolocationEnabled (webView1 As WebView, Enabled As Boolean)
      Sets whether Geolocation is enabled.
    • setJavaScriptCanOpenWindowsAutomatically (webView1 As WebView, flag As Boolean)
      Tell javascript to open windows automatically.
      This applies to the javascript function window.open().
    • setLightTouchEnabled (webView1 As WebView, enabled As Boolean)
      Enables using light touches to make a selection and activate mouseovers.
    • setLoadWithOverviewMode (webView1 As WebView, overview As Boolean)
      Set whether the WebView loads a page with overview mode.
    • setLoadsImagesAutomatically (webView1 As WebView, flag As Boolean)
      Tell the WebView to load image resources automatically.
    • setMediaPlaybackRequiresUserGesture (webView1 As WebView, Requires As Boolean)
      Sets whether the WebView requires a user gesture to play media.
      The default is true.
    • setMinimumFontSize (webView1 As WebView, size As Int)
      Set the minimum font size.
      size - A non-negative integer between 1 and 72.
    • setPluginState (webView1 As WebView, state As String)
      Tell the WebView to enable, disable, or have plugins load on demand.
      On demand mode means that if a plugin exists that can handle the embedded content, a placeholder icon will be shown instead of the plugin.
      When the placeholder is clicked, the plugin will be enabled.
    • setSaveFormData (webView1 As WebView, save As Boolean)
      Store whether the WebView is saving form data.
    • setSavePassword (webView1 As WebView, save As Boolean)
      Store whether the WebView is saving password.
    • setSupportZoom (webView1 As WebView, support As Boolean)
      Set whether the WebView supports zoom.
    • setUseWideViewPort (webView1 As WebView, use As Boolean)
      Tell the WebView to use the wide viewport.
    • setUserAgentString (webView1 As WebView, userAgent As String)
      Set the WebView's user-agent string.
      If the string "userAgent" is null or empty, it will use the system default user-agent string.
    • supportZoom (webView1 As WebView) As Boolean
      Returns whether the WebView supports zoom.

Library files and demo attached to this post.
The demo is not a full demo - it simply shows the syntax to use for the getSavePassword and setSavePassword methods.
But you can soon update the demo to experiment with any of the other settings.

Martin.
 

Attachments

  • WebViewSettings_v_1_31.zip
    12.5 KB · Views: 3,793
Last edited:

warwound

Expert
Licensed User
Longtime User
WebViewSettings updated to version 1.2

As requested i have added two new methods:

getDisplayZoomControls (webView1 As WebView)

Returns true if the on screen zoom buttons are displayed.
Only supported on Android API level 11 and later.

setDisplayZoomControls (webView1 As WebView, Enabled As Boolean)

Sets whether the on screen zoom buttons are displayed.
A combination of built in zoom controls enabled and on screen zoom controls disabled allows for pinch to zoom to work without the on screen controls.
Only supported on Android API level 11 and later.

B4X:
Sub Process_Globals
End Sub

Sub Globals
   Dim WebView1 As WebView
   Dim WebViewSettings1 As WebViewSettings
End Sub

Sub Activity_Create(FirstTime As Boolean)
   WebView1.Initialize("")
   Activity.AddView(WebView1, 0, 0, 100%x, 100%y)
   
   WebViewSettings1.setDisplayZoomControls(WebView1, False)
   
   WebView1.LoadUrl("http://www.b4x.com/forum/index.php")
   
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Unfortunately these two methods are only supported in Android API since level 11 (Android 3.0).
I have no device to test these new methods on so if anyone can confirm that they work it would be appreciated.

Version 1.2 of WebViewSettings is attached to post #1 in this thread.

Martin.
 

nad

Active Member
Licensed User
Longtime User
I will check it now.

One thousand thanks Martin i really appreciate it

Thanks a lot. Time to hide those pesky buttons :)

Cheers!
 

nad

Active Member
Licensed User
Longtime User
Hi again Martin,

Fot Froyo is not working. For ICS is working wonderfully.
Well that is an Android limitation, in some months more people will have it working as they upgrade. I guess there is nothing else we can do.

Thanks a lot!!

Cheers
 

warwound

Expert
Licensed User
Longtime User
WebViewSettings updated to version 1.30

This updated adds just a single new method:

setGeolocationEnabled (webView1 As WebView, Enabled As Boolean)

Sets whether Geolocation is enabled.

Version 1.30 of WebViewSettings is attached to the first post in this thread.

Martin.
 

warwound

Expert
Licensed User
Longtime User

infotxt

New Member
Licensed User
Longtime User
WebView and PhoneSMS

Would like to ask if it's possible for an HTML / website loaded in a WebView to be able to access the PhoneSMS component to be able to send an SMS?

Any suggestion on how to do this would greatly be appreciated :)
 

warwound

Expert
Licensed User
Longtime User
Well i just tried to do this but the SMS didn't get sent.
I tried on a Gingerbread and an ICS device.

Here's the B4A code:

B4X:
'Activity module
Sub Process_Globals

End Sub

Sub Globals
   Dim PhoneSms1 As PhoneSms
   Dim WebViewExtras1 As WebViewExtras
   Dim WebView1 As WebView
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("Main")
   
   WebViewExtras1.addJavascriptInterface(WebView1, "B4A")
   
   WebView1.LoadUrl("file:///android_asset/send_sms.html")
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub PhoneSms1_SmsDelivered (PhoneNumber As String, Intent As Intent)
   Log("PhoneSms1_SmsDelivered")
End Sub

Sub PhoneSms1_SmsSentStatus (Success As Boolean, ErrorMessage As String, PhoneNumber As String, Intent As Intent)
   Log("PhoneSms1_SmsSentStatus: "&Success)
   If Success=False Then
      Log(ErrorMessage)
   End If
End Sub

Sub WebView1_SendSMS(MobileNumber As String, SMSMessage As String)
   Log(MobileNumber)
   Log(SMSMessage)
   PhoneSms1.Send(MobileNumber, SMSMessage)
End Sub

And the webpage i created:

PHP:
<!DOCTYPE html>
<html>
   <head>
      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
      <style type="text/css">
         table {
            border-collapse: collapse;
         }
      </style>
      <script type="text/javascript">
         function sendSMS(form){
            var mobileNumber=form.mobileNumber.value;
            var smsMessage=form.smsMessage.value;
            
            //   ideally you'd now validate the mobileNumber and check that the smsMessage is not empty or too long
            
            B4A.CallSub('WebView1_SendSMS', true, mobileNumber, smsMessage);
            form.reset();   //   optional - clear the form when the SMS is sent
            return false;   //   return false prevents the form from submitting itself
         }
      </script>
   </head>
   <body>
      <div>
         <form action="" method="GET" onsubmit="return sendSMS(this)">
            <table style="width: 100%">
               <tr>
                  <th colspan="2">
                     SMS Sender
                  </th>
               </tr>
               <tr>
                  <td>
                     To:
                  </td>
               </tr>
               <tr>
                  <td colspan="2">
                     <input type="tel" name="mobileNumber" value="" style="width: 100%">
                  </td>
               </tr>
               <tr>
                  <td>
                     Message:
                  </td>
               </tr>
               <tr>
                  <td colspan="2">
                     <textarea name="smsMessage" style="width: 100%"></textarea>
                  </td>
               </tr>
               <tr>
                  <td align="center">
                     <input type="reset" value="Reset">
                  </td>
                  <td align="center">
                     <input type="submit" value="Send">
                  </td>
               </tr>
            </table>
         </form>
      </div>
   </body>
</html>

No SMS is sent!
Maybe you'd like to try to get it working?

Martin.
 

Attachments

  • WebViewSendSMS.zip
    7.2 KB · Views: 278

infotxt

New Member
Licensed User
Longtime User
I am getting this error:

Error description: Unknown type: webviewextras
Are you missing a library reference?

Help? :)
 

airblaster

Active Member
Licensed User
Longtime User
I'm trying to use WebViewSettings to set some settings, e.g.
B4X:
WebViewSettings1.setDefaultZoom(WebView1, "CLOSE")
.
But for some reason, there seems to be no change as compared to
B4X:
WebViewSettings1.setDefaultZoom(WebView1, "FAR")

Do I need to add something else for this to work? E.g. a WebChromeClient?
 

warwound

Expert
Licensed User
Longtime User
No there is no requirement for other libraries or the WebChromeClient.

I've noticed that setting the DefaultZoom can be unpredictable and have always found the reason to be the webpage that is being loaded.
Some webpages can be scaled by the WebView and if you set the DefaultZoom you'll see the setting take effect.
Other webpages cannot be scaled - the CSS and HTML is written in a way that seems to prevent the WebView from performing any scaling.

Can you try various different webpages and see if the setting works with some webpages but not others?

Martin.
 

airblaster

Active Member
Licensed User
Longtime User
I tried heise.de, both mobile and desktop version. Same result, unfortunately. Same goes for Google.

Btw, I have problems with WebViewSettings1.setDisplayZoomControls as well - it works on heise.de, but not on the website I actually want to use.

Google's Documentation for setDefaultZoom says "This must be called from the UI thread". I suppose this is the case with WebViewSettings?
 

warwound

Expert
Licensed User
Longtime User
Take a look at the attached project, it uses the all new but so far unpublished version of WebViewExtras.
The new version is a complete re-write and offers far more options - but a lot of it is untested so i have not yet uploaded it to the forum.
Reference for this new version can be found here: WebViewExtras.

B4X:
Sub Process_Globals
   Dim LastUrl As String=""
   Dim LastZoom As String=""
End Sub

Sub Globals
   Dim UrlSpinner As Spinner
   Dim WebView1 As WebView
   Dim WebViewExtras1 As WebViewExtras
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("Main")
   Activity.AddMenuItem3("CLOSE", "MenuItem", Null, True)
   Activity.AddMenuItem3("FAR", "MenuItem", Null, True)
   Activity.AddMenuItem3("MEDIUM", "MenuItem", Null, True)
   
   '   after initializing the WebViewExtras object it can be used instead of the WebView
   '   WebViewExtras contains all methods of WebView plus many more
   
   WebViewExtras1.Initialize(WebView1)
   
   If LastUrl<>"" Then
      WebViewExtras1.LoadUrl(LastUrl)
   End If
   
   If LastZoom<>"" Then
      WebViewExtras1.GetSettings.SetDefaultZoom(LastZoom)
   End If
   
   UrlSpinner.AddAll(Array As String("http://www.heise.de/", "http://www.google.com/", "http://www.kingslynn-forums.co.uk/index.php"))
   
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub MenuItem_Click
   LastZoom=Sender   '   Sender will be the Text of the clicked MenuItem
   Select LastZoom
      Case "CLOSE"
         WebViewExtras1.GetSettings.SetDefaultZoom("CLOSE")
      Case "FAR"
         WebViewExtras1.GetSettings.SetDefaultZoom("FAR")
      Case "MEDIUM"
         WebViewExtras1.GetSettings.SetDefaultZoom("MEDIUM")
   End Select
End Sub

Sub UrlSpinner_ItemClick (Position As Int, Value As Object)
   LastUrl=Value
   WebViewExtras1.LoadUrl(LastUrl)
End Sub

The Activity starts - no url is loaded.
Use the Spinner to select a url and then try the different DefaultZoom settings - i see various changes in the appearance when the DefaultZoom is changed.
(I'm testing this on a Galaxy Tab2 running Jelly Bean).

The effect should be the same using the old versions of WebViewExtras and WebViewSettings.
All code in an Activity module runs in the UI thread so you haven't got a problem there.

The project and new version of WebViewExtras are attached - can you try them on your device and on the webpage you are trying to view and post with your results?

Martin.
 

Attachments

  • DefaultZoom_20130521.zip
    43.6 KB · Views: 257

airblaster

Active Member
Licensed User
Longtime User
For some reason, your demo app works just fine.
I tried many different things now to get it working, but it just doesn't seem to work in my app.
Btw, I really like the new WebViewExtras, great work!
 

airblaster

Active Member
Licensed User
Longtime User
Finally figured it out...
The 3rd Party HTML that is received through an API sets
HTML:
<meta name="viewport" content="target-densitydpi=device-dpi, width = 320, user-scalable = 0"/>
The part
B4X:
target-densitydpi=device-dpi
is what causes all the problems.
Is there any way to modify the HTML that is loaded after clicking a link in a WebView? E.g. an Event that receives the original HTML and returns the modified HTML?
 

warwound

Expert
Licensed User
Longtime User
You can wait for the WebView PageFinished(Url As String) event to be raised and inject some javascript into the page that will get the loaded HTML and send it to a b4a Sub:
http://www.b4x.com/forum/basic4andr...9408-read-content-html-string.html#post111864

But a better solution seems to be to again wait for the PageFinished event to be raised and then inject some javascript that will modify the viewport meta tag (on the fly).
Take a look at this search:
https://www.google.co.uk/search?q=javascript+modify+meta+tag&ie=UTF-8&oe=UTF-8

I'd try to inject some javascript that does this:

B4X:
var metaTags=document.getElementsByTagName('meta');
for(var i=0; i<metaTags.length; i++){
  if(metaTags[i].name=='viewport'){
    metaTags[i].content='????';  // here insert the new content value
  }
}

That's untested by the way.
You might want instead to remove the viewport meta tag instead of modifying it:

B4X:
var metaTags=document.getElementsByTagName('meta');
for(var i=0; i<metaTags.length; i++){
  if(metaTags[i].name=='viewport'){
    metaTags[i].parentNode.removeChild(metaTags[i]);
  }
}

Martin.
 
Top