惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

IT之家
IT之家
H
Help Net Security
GbyAI
GbyAI
博客园_首页
G
Google Developers Blog
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
月光博客
月光博客
美团技术团队
B
Blog RSS Feed
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
博客园 - 叶小钗
有赞技术团队
有赞技术团队
T
The Blog of Author Tim Ferriss
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
Microsoft Azure Blog
Microsoft Azure Blog
罗磊的独立博客
云风的 BLOG
云风的 BLOG
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed

ashishb.net

A day in Luxembourg - the richest country in the world I was asked to install malware during a fake interview Book summary: Breakneck - China's quest to engineer the future by Dan Wang Book summary: How to Teach Your Baby to Read Book Summary: The Discontented Little Baby Book by Pamela Douglas Introducing Amazing Sandbox - run third-party tools and AI agents securely on your machine Why software outsourcing gets a bad reputation? Book summary: The Natural Baby Sleep Solution by Polly Moore A day in Antwerp, Belgium Journey of online influencers Two days in Brussels, Belgium Shortcuts - when we love them and when we don't A visit to Rakhigarhi Three days in overhyped Paris Empty Japan, crowded Tokyo The real lock-in in GitHub is not the code, but the stars 11-day Norwegian Breakaway East Caribbean cruise Sanskrit and Sri Lankan Air Force Use REST with Open API The Achilles heel of American capitalism Costa Rica in 4 days At a juice stall in Sri Lanka A short stay at Warsaw, Poland Best practices for using Python & uv inside Docker Two days in Vilnius, Lithuania How IntelliJ IDEs waste disk space Pregnancy Why there aren't many digital nomads from India Two days in Riga, Latvia To keep your machine secure, run third-party tools inside Docker
Cross-language bridge error handling: JS-to-Java Example
Ashish Bhatia · 2018-11-02 · via ashishb.net

All languages have certain semantics for dealing with error cases. C deals with them by setting error codes. Java deals with them by throwing exceptions. JavaScript deals with them by throwing exceptions as well but unlike Java, it does have any concept of checked Exceptions. The JS interpreter just stops. And this has some interesting implications in hybrid scenarios like a Webview based app.

Consider a simple Android app where most of the code is in JavaScript but is making a request to Java layer.

1
2
3
4
5
<html>
    <head/>
    <!-- Invoke getContacts() on the Javascript bridge object referenced via “JsInterface” tag on click -->
    <Button onClick='ContactJsInterface.getContacts()'>Click me</Button>
</html>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// MainActivity in Kotlin
class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
        ....
        // Load the above string into webview
        webView.loadDataWithBaseURL("about:blank", htmlPage, "text/html", null, null)
        webView.settings.javaScriptEnabled = true
        // Add a WebkitJsInterface object and tag it with "ContactJsInterface", so that,
        // JsInterface.getContacts maps to WebKitJsInterface.getContacts
        webView.addJavascriptInterface(new WebkitJsInterface(this), "ContactJsInterface")
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// The Javascript interface object in Kotlin
class WebkitJsInterface(context: Context) {
    private val mContext = context

    // ContactJsInterface.getContacts() maps to this method
    @JavascriptInterface
    fun getContacts() {
        mContext.contentResolver.query(
            ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null)
    }
}

After starting the app, check that the READ_CONTACTS is revoked or revoke it with adbe

1
adbe permissions revoke net.ashishb.jstojavademo contacts

Now, when you click the “Click me” button, you will see a SecurityException in the logs but the app won’t crash. If you check Thread’s name via Thread.currentThread().name, it will return JavaBridge. It seems any Exception thrown on this thread is simply swallowed. This won’t show up in analytics or crash log reports. Your Javascript code on return simply won’t be executed. And your app will appear unusable. This is worse than crashes. crashes at least give the app a chance to get out of a bad state.

This is worse than crashes. crashes at least give the app a chance to get out of a bad state.

Remedy

Sending error information across languages is hard. At the bare minimum, every such call should be encapsulated with a try-catch which catches Exception. For severe unexpected errors, it might not be bad to let the app crash, as you would, while writing the Java code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@JavascriptInterface
fun getContacts() {
    try {
        getContactsUnsafe()
    } catch (e : Exception) {
        if (isSevereException(e)) {
            rethrowOnMainThread(e)
        } else {
            logError(e)
        }
    }
}

private fun logError(e: Exception) {
    Log.e("WebkitJsInterface", "Error occurred", e)
}

private fun rethrowOnMainThread(e: Exception) {
    Handler(Looper.getMainLooper()).post { throw e }
}

private fun getContactsUnsafe() {
    mContext.contentResolver.query(
        ContactsContract.Contacts.CONTENT_URI,
        null, null, null, null
    )
}

Full code for this blog post is posted on Github