Manual - All you need to know to use UniWebView well


Download and Import

Download and import the .unitypackage file into your project (If you already have your own AndroidManifest.xml in the project, backup it and uncheck the tick before this file when importing, then follow the merge instruction below to merge the file correctly.

Upgrade From UniWebView 1.x

If you are using UniWebView 1.x in your project, you have to remove it manually from your project first, and then import the UniWebView 2 package into your project. Please follow these steps to upgrade your version.

  • Backup your project.
  • Remove the UniWebView folder under your Assets folder in your project.
  • Remove Plugins/Android/UniWebView.jar, Plugins/iOS/UniWebView.mm and all files starts with UniWebView in the Plugins folder.

Finally, you can import the UniWebView 2 package. Done. You can keep your original AndroidManifest.xml file, since there is no change on that file in the new version.


Play with demo scenes

The best way to get started with UniWebView is playing with the demo scenes. The demo scenes are under UniWebView/Demo folder. You can either just run an individual demo, or add them to your build scenes in order.

These demos shows the basic usage of UniWebView. You can find the scripts control the scene in the same folder of the scene file. When you are ready to explore UniWebView more, you can follow the below guide to know detail about this package.


Add UniWebView as component

You can use the UniWebViewObject prefab under UniWebView/Prefab to get start quickly. Just drag and drop it to the scene you want to show web content, and change the Url property to an url you want it to load in the Inspector panel. If Load On Start and Auto Show When Load Complete are on, UniWebView will load the url automatically when the script get loaded, then show the web page above your scene when the load finished.

If you want more control of the web view, you may want to attach the UniWebView.cs as a Component to your own game object in the scene. You can either drag this file to the game object, or add it by code. If you have no idea what the GameObject and Component is, please refer to GameObjects part in Unity manual to learn more.


Setup UniWebView, Load web content and Show

After you adding UniWebView as a component of the game object, you may want to do some basic setup to make it work. First of all, you may want to get a reference to the component by Unity's GetComponent method. Suppose you are working on a script attached to the same gameObject which UniWebView.cs is on, and you have already declared a ivar as UniWebView _webView;

// Find the UniWebView component on the gameObject.
// It is supposed you have already dragged this script to the same gameObject which UniWebView on.
// Or you will get a null exception :(
_webView = GetComponent<UniWebView>();

// Listen to some event of UniWebView
_webView.OnLoadComplete += OnLoadComplete;
_webView.OnReceivedMessage += OnReceivedMessage;
_webView.OnEvalJavaScriptFinished += OnEvalJavaScriptFinished;

In the example, you listened some events of UniWebView. The full list of events which UniWebView will raise can be found in the Events of script reference of UniWebView.

Then, set the size of the web view and the url you want to load. UniWebView uses a relative way to decide the size. You can specify the distance between the screen edge and the web view edge and UniWebView will layout itself follow it. You will use UniWebViewEdgeInsets and set the insets property of UniWebView.

The url property is quite straightforward. Just set the url address you want to load.

// Almost full screen but 5 points gap in each edge.
_webView.insets = new UniWebViewEdgeInsets(5,5,5,5);
// Set a url string to load
_webView.url = "http://uniwebview.onevcat.com/demo/index.html";

Now, you are ready to load the url and show the web page to your users! You can call Load() method on the web view component to begin load the url. When your content is ready or failed, the OnLoadComplete event is raised. You can listen to it and decide show the page or not, as described below:

// Tell the web view begin to load the url just set.
_webView.Load();

// Then wait for the OnLoadComplete event

//...

// The listening method of OnLoadComplete method.
void OnLoadComplete(UniWebView webView, bool success, string errorMessage) {
  if (success) {
    // Great, everything goes well. Show the web view now.
    webView.Show();
  } else {
    // Oops, something wrong.
    Debug.LogError("Something wrong in web view loading: " + errorMessage);
  }
}

If you do not want to implement the listener or there is no need to handle the fail result, you can set the autoShowWhenLoadComplete property to true to let UniWebView open itself when load successfully. You can also call Show() first and then do a Load(), a spinner will show up for you until the load progress finishes. All up to you!


Communication between web view and Unity game

The UniWebView would become USELESS if it is can only present a webpage. By using the package, you can easily talking to the web view from your game or receiving the message it sends out. You can follow the structures below to get some detail information.

UniWebView to Unity

The suggested way is using a url scheme to send message to Unity. UniWebView will listen to a url starting with uniwebview://. Whenever this kind of url is loaded (regularly it would be a click on the url link in your webpage by user), UniWebView will parse it to a UniWebViewMessage object and then raise the OnReceivedMessage event. A UniWebViewMessage contains a path string to represent the path in the url, and a args dictionary to represent the parameters in the url.

For example, click on a link: uniwebview://move?direction=up&distance=1 will be parsed as:

path = "move"
args = {
    direction = "up",
    distance = "1"
}

in a UniWebViewMessage, and you can implement your logic in a listener for OnReceivedMessage.

void OnReceivedMessage(UniWebView webView, UniWebViewMessage message) {
   Debug.Log(message.rawMessage);
   if (string.Equals(message.path, "move")) {
      // It is time to move!

      // In this example:
      // message.args["direction"] = "up"
      // message.args["distance"] = "1"
   }
}

There is a demo with step-by-step tutorial in the package to show how to use it in detail. Check it whenever you want. You can also add customized url schemes and make them sending message to UniWebView. See AddUrlScheme in reference for more.

Unity to UniWebView

You can run any javascript with the web page from Unity game. The javascript can be either a block of code embedded in the webpage, or a string of js code wrote in your game script. By using EvaluatingJavaScript, you can call and run javascript, so you can talk to your page to do something you want. If you are interested in the return value of the js, you can listen to the OnEvalJavaScriptFinished event and handle the result there.

In the Mac Editor, the alert in the page would not pop up due to some technology issues (But the js code itself will be excuted as expected).


Other features

Besides of the basic web page presenting and communication, there are some other feature UniWebView for you.

Background transparent - In iOS, there is a gray background by default in web view. You can use SetTransparentBackground to set the back ground transparent.

Spinner when loading - We added a spinner to both iOS and Android web view when it in loading progress, to improve the experience. You can disable and customize the label text by SetShowSpinnerWhenLoading and SetSpinnerLabelText.

Back button support and nav toolbar - Users can use the back button on the Android device to navigation between web pages as they do in native browser. For iOS, there is a default toolbar with nav button ready.

Go back and go forward - Just behaves as a browser, you can control the webpage navigation in your game, by GoBack and GoForward method.

Clean cache - The web view will keep the url request by default, which may cause an old page showed

even if you update your web page. Use CleanCache to solve this problem.

Play youtube video with the web view - Just load the url and it can play, so simple.

Load local files and html string - By giving a local file url, or calling LoadHTMLString with a html string value, you can load the content locally.

Mutil use - You can not only use it for html and web page, but also to show some images.

More than one web view - If you want multiple web views in your game, just instantiate another gameObject and add the script to it.


Feel free to explore the script refernce for the full methods list. Also let us know if you have some common request and we will add it soon!

Merge Guide How to deal with annoying AndroidManifest file


Check your AndroidManifest.xml

UniWebView needs correct AndroidManifest.xml to work. If you do not target for Android, or there is no AndroidManifest.xml file yet in your project (which should be under Assets/Plugins/Android) when importing UniWebView, you can skip this section. Otherwise, there might be conflict and please follow the steps below to update your existing manifest file.

If you are NOT using Unity's default activity (something like com.unity3d.player.UnityPlayer*Activity) as the main activity, you may need to refer to the next section Recompile Guide to recompile the UniWebView package from source for Android to let it work with your game.

If you already have an AndroidManifest.xml file in your project, you should not import the AndroidManifest.xml file from UniWebView's package anymore. Instead, you need to update that file yourself. Don't worry about it, it's fairly simple and just takes less than 2 minutes usually. After you importing the package to your project without AndroidManifest.xml, you could follow these steps to make it work:

  1. Open your original AndroidManifest.xml file with any text editor you like. The file should be loacated in Assets/Plugins/Android.
  2. Search for android.intent.action.MAIN in your AndroidManifest.xml. Regularly, there should be one and only one match in the file.
  3. Merge and add as following steps:

Merge

(1) The result of Step 2 should be located in a pair of <activity> and </activity> tags. Insert the two lines in the box below if they are not existing. You should add them just above the </activity> tag.

<meta-data android:name="android.app.lib_name" android:value="unity" />
<meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />

(2) In same the <activity...> tag, change the value of android:name to "com.onevcat.uniwebview.AndroidPlugin". This will use the UniWebView's activity to start your game. By doing so we, can avoid some issues for web view in Android. If you are using a main activity other than com.unity3d.player.UnityPlayerNativeActivity, com.unity3d.player.UnityPlayerActivity or com.unity3d.player.UnityPlayerProxyActivity, you have to modify the source code shipped with UniWebView to your own customization. Please refer to the next section Recompile Guide to know more about it.

(3) In the same <activity...> tag, add android:hardwareAccelerated="true" and android:windowSoftInputMode="adjustResize" into it. This will enable the html5 feature for Android.

After these three steps, the activity would be something like this:

<activity android:name="com.onevcat.uniwebview.AndroidPlugin"
    android:label="@string/app_name"
    android:hardwareAccelerated="true"
    android:windowSoftInputMode="adjustResize"
    android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <meta-data android:name="android.app.lib_name" android:value="unity" />
    <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
</activity>

(4) At last, add the permission for accessing to Internet, if there is not one yet. Add the next line just before the end of manifest, the line above the </manifest> tag.

<uses-permission android:name="android.permission.INTERNET" />

Great! Now you should have done with it. Get some beer for yourself, cheers.

Recompile Guide Make it work with other third party plugins


Overview

If you are not using a customized activity or some other third party customized activity as you Android main activity, you can skip this section.

By default, Unity is using an activity called UnityPlayerActivity in Android as the main activity. UniWebView needs to run in its own activity as the main activity avoid some potential issues such as input handler or background switch. The activity which UniWebView is using by default is a subclass of UnityPlayerActivity, so it will not break anything of origin Unity. But sometimes you have to let other plugin's activity to run as the main activity. Fortunately, UniWebView is shipped with original source code for Android, so you can modify the source code and recompile it as you need. This guide will show you how to do it.

You can find some precompiled jar files in /UniWebView/ThirdPartyJar.zip. If the one you need happens there, you can use the corresponding file to replace the original UniWebView.jar in Plugins/Android, then just do the last step below to make your AndroidManifest.xml correct.


Before Start

  1. You need the SDK of Android installed. Please refer to the Android developer site for more information.
  2. You need Apache Ant installed to compile java from command line. This tool is installed on Mac by default, you can run which ant in terminal to confirm if it is installed. If not, please refer to this post or the ant's official site for more information to install it.
  3. Download the UniWebView's customize compile script package from here and unzip it to a folder (we will call it "compile folder" later). This package is for Unix based system (such as Mac), but you can adapt it for Windows if needed easily.
  4. And of course, you need the source code of UniWebView Android, which is bundled with this package under the folder /Assets/UniWebView/Source/Android/ after you import it.

Let Us Begin

1. Confirm Main Activity

Check the main activity you are using now. You can search in the AndroidManifest.xml file located at Assets/Plugins/Android/. Open the file, search by the keyword "android.intent.action.MAIN", it should be one and only one in this file if you are using a customize main activity. This keyword is located between a pair of tag <activity> and </activity>, and an "android:name" key will follow it indicates the name of your main activity. Remember this name, and we will use it later. Now let's suppose it's called "com.otherCompany.otherPlugin.OtherActivity".

2. Find the jar file for OtherActivity.

Most Android plugins are provided as jar files. So you should find out which jar file contains the declaration of OtherActivity. It should be imported when you importing that plugin and located at the Assets/Plugins/Android/ or its subfolder. Then remember the path of this jar file. Let's suppose it to be "Assets/Plugins/Android/OtherPlugin.jar".

3. Copy Source

Copy all the source code of UniWebView Android to the src/com/onevcat/uniwebview folder under the compile folder.

4. Modify AndroidPlugin.java

Modify the file AndroidPlugin.java you just copied. Replace the UnityPlayerActivity to the name of your current main activity, in this tutorial, it is "com.otherCompany.otherPlugin.OtherActivity".

5. Modify Build Script

Modify the build script named "install.sh" under the compile folder. You should change the first several lines of this file:
  • Change the value of UNITYLIBS to your Unity Android Player jar file path. You just need to modify the folder name in Application in most cases. I f you are using a version before Unity 4.5, please comment the original one and use the one below. You have to specify a correct path for Unity Android class jar file here.
  • Change the value of OTHERLIBS to the path you got in step 2. The script will refer to the path for compiling later.
  • Change the value of ANDROIDCOMMAND to the where your andriod command is. It is located in your Android SDK path, under the tools folder. But it could be different in some platform.

6. Recompile Package

Now we can recompile it. Change the working path to the compile folder in terminal. Then run ./install.sh. If everything goes well, you will find a file called UniWebView.jar under the same folder. Copy it to your Project's /Assets/Plugins/Android/ and replace the old one.

7. Update Manifest.xml

Open the AndroidManifest.xml file we mentioned in step 1. Replace the main activity name of your main activity to "com.onevcat.uniwebview.AndroidPlugin". Of course, remember to add the <meta-data android:name="android.app.lib_name" android:value="unity" /> to this activity (the final content of the main activity should be the same as the Merge AndroidManifest.xml section. Then you will find it works!

Congratulations, you made it works! Have a beer for yourself because it is really a tough thing. If you encountered any problems during it, feel free to contact us for help.