Giter Site home page Giter Site logo

cdeutsch / jsbridge Goto Github PK

View Code? Open in Web Editor NEW
92.0 4.0 22.0 193 KB

Simpler bidirectional communication between JavaScript in a UIWebView and C# in your native app.

Home Page: https://components.xamarin.com/view/jsbridge

License: MIT License

C# 87.18% JavaScript 12.82%

jsbridge's Introduction

JsBridge

Simpler bidirectional communication between JavaScript in a UIWebView and C# in your native app.

Requirements

  • Xamarin.iOS 8.6 is required for Unified support due to a bug in lower versions.

Usage

Reference the JsBridge project or DLL in your Project.

In the html files where you want to use JsBridge, include a copy of the mt.js file.

<script src="js/mt.js"></script>

Alernatively you can call InjectMtJavascript on your UIWebView but you will have to call it everytime a new page is loaded and since you usually have to wait until the page is loaded to do so, it is recommended to include mt.js instead to insure it's available when you need it.

Browser Side

From a UIWebView you can do the following:

Log to Native side

Mt.API.info( 'This message will print on the native side using Console.WriteLine' );

Fire Events on the Native side

Mt.App.fireEvent('promptUser', { 
    msg: 'Hi, this msg is from the browser.',
    extra: 'You can send more then one property back',
    question: 'Did you get this message?',
    answer: 42
});

Subscribe to Events triggered from the Native side

Mt.App.addEventListener('handleNativeEvent', function(data) {

    if (data && data.ArbitraryProperty) {
	    console.log( data.ArbitraryProperty );
    }

});

Native Side

From your Xamarin application you can interact with your UIWebView as follows:

Fire Events on the Browser side

viewController.WebView.FireEvent( "handleNativeEvent", new {
	Message = "The Native code says hi back. ;)",
    ArbitraryProperty = "more properties",
    Success = true
});

Subscribe to Events triggered from theBrowser side

viewController.WebView.AddEventListener( "promptUser", delegate(FireEventData arg) {

    // show a native action sheet
    BeginInvokeOnMainThread (delegate { 
        var sheet = new UIActionSheet ( arg.Data["question"].ToString() );
        sheet.AddButton ( "Yes" );
        sheet.AddButton ( "No" );
        sheet.CancelButtonIndex = 1;
        sheet.ShowInView ( viewController.View );
    });

});

History

12/18/2014

  • Added Xamarin.iOS Unified support (Xamarin.Mac Unified support is broken)

1/12/2014

  • Merged "jsbridge mac implementation" from codingday

7/9/2013

  • Updated to use jXHR library so you can use JsBridge across domains and on remote sites.

6/29/2013

  • Changed 'Func<>' into 'Action<>' call for the latest version of MonoTouch

5/1/2012

  • Initial Release

jsbridge's People

Contributors

cdeutsch avatar certen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

jsbridge's Issues

AddEventListener Application Crash

Hello Team,

I am currently using the D3 Graph in my Xamarin.iOS project. While plotting the graph on UIWebView I am adding Event Listener through AddEventListener method. But this method is calling multiple time as I visit the respective controller. So while we are switch between the controller, the application gets crash showing the below StackTrace.

StackTrace
2019-09-24 20:04:46.941 [App_Name][418:11433666] ConvertToNSExceptionAndAbort
2019-09-24 20:04:46.944 [App_Name][418:11433666] Inserted Xamarin Exception Stack Line!
2019-09-24 20:04:46.944 [App_Name][418:11433666] Name: System.InvalidOperationException
2019-09-24 20:04:46.944 [App_Name][418:11433666] Message: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.Xamarin Exception Stack:
at System.Collections.Generic.List1+Enumerator[T].MoveNextRare () [0x00013] in <91e0283eca55453fa9b161bf2de4edfd>:0 at System.Collections.Generic.List1+Enumerator[T].MoveNext () [0x0004a] in <91e0283eca55453fa9b161bf2de4edfd>:0
at System.Linq.Enumerable+WhereListIterator`1[TSource].MoveNext () [0x0004e] in <825255c699d046a482fee36362eb0c49>:0
at cdeutsch.JsBridge.JsEventFired (cdeutsch.FireEventData feData) [0x0005b] in <467146c6f412491191a720507ed7938e>:0
at cdeutsch.AppProtocolHandler.StartLoading () [0x00109] in <467146c6f412491191a720507ed7938e>:0

Js Bridge is not woking for JS to C# call

Hi,
I had set up the jsBridge Componene for my xamarin.Ios App. I am able to call the javascript frpm C# in ViewDidLoad event. But i am unable to get through the call from JS to C#.Please find the code snippet below

UIViewController.cs

public override void ViewDidLoad ()
{
base.ViewDidLoad ();

        //// load our local index.html file 
        // get path to file.

// string path = NSBundle.MainBundle.PathForResource( "www/index", "html" );
// // create an address and escape whitespace
// string address = string.Format("file:{0}", path).Replace( " ", "%20" );
string fileName = "www/index1.html"; // remember case-sensitive
string localHtmlUrl = Path.Combine (NSBundle.MainBundle.BundlePath, fileName);
webView.LoadRequest(new NSUrlRequest(new NSUrl(localHtmlUrl, false)));
webView.ScalesPageToFit = false;

        webView.LoadFinished += (object sender, EventArgs e) => {
            this.webView.FireEvent( "doBrowserStuff", new {
                Message = "The Native code says hi back. ;)",
                Extra = "more properties",
                Success = true
            });




        };
        // be sure to enable JS Bridge before trying to fire events.


        this.webView.AddEventListener( "doNativeStuff", delegate(FireEventData arg) {
            Console.WriteLine("doNativeStuff Callback:");   
            Console.WriteLine(arg.Data["msg"]);

            // trigger doBrowserStuff event in browser.

        });

        // listen for the nativeSheet event triggered by the browser.
        /*webView.AddEventListener( "nativeSheet", delegate(FireEventData arg) {

             show a native action sheet
            BeginInvokeOnMainThread (delegate { 
                var sheet = new UIActionSheet ( "Your Action Sheet" );
                sheet.AddButton ( arg.Data["msg"].ToString() );
                sheet.AddButton ( "Cancel" );
                sheet.CancelButtonIndex = 1;
                sheet.ShowInView ( View );
            });

        });*/


        // Perform any additional setup after loading the view, typically from a nib.
    }

Index.HTML

    <title></title>
    <script src="js/mt.js"></script>

    <script>


        Mt.App.addEventListener('doBrowserStuff', function(data) {

            alert('hi');

                //alert(data.Message);
            });

        window.onload = function(e) {


            Mt.API.info( 'log "loaded" call on native side' );
            alert('window load');

            // listen for doBrowserStuff event triggered from native code.


            // fire doNativeStuff in native code.
        //  Mt.App.fireEvent('doNativeStuff', { 
          //      msg: 'Hi, this msg is from the browser.',
            //    extra: 'You can send more then one property back',
              //  answer: 42
            //});

        };

        // do this, to write console log calls to Native 
        //    NOTE: this is overridden in next statement, just here to show you how to do it.


    </script>

</head>
<body>
<div role="main">
        <p>Loading MonoTouch JsBridge Demo...</p>
        <a href="javascript:Mt.App.fireEvent('doNativeStuff', { msg: window.prompt(' Enter a cool name for you action ') });">Click Me to show a Native Action Sheet</a>
    </div>



</body>

JSBridge doesn't work for Razor views

Hi,

I'm attempting to use this cool library in an app that users Razor views (which is a very cool feature of Xamarin) however I don't seem to be able to get it working.

Looking at the code, it seems that it because JSBridge uses a protocol handler, perhaps it cannot work with LoadHtmlString, and instead needs an actual request ?

A workaround might be for me to save my razor generated HTML as a file on disk and then load it, but seems like it might be slow. Or I could have a basic HTML file then load in via the JSBridge the rest of the DOM generated from Razor?

Just wondering if I'm missing something and there's actually a way for it to work easily?

Thanks!

mt.js uses synchronous calls - is there a reason for this?

Excellent library here!

One thing I've noticed is that mt.js appears to send all requests synchronously, resulting in thread blocking. In our case, it's very noticeable with a HTML5 slider control, that calls Mt.App.fireEvent many times in succession as its dragged.

Is there a reason that this couldn't be modified to make requests asynchronously instead?

Working with https web pages

Hi,

We are using JsBridge Unified library on Xamarin iOS app to communicate between web page and native functionality. We have a UIWebView which renders a web page and it invokes camera from device to scan a bar code. The library was working fine until we were serving http pages. Recently, we changed them to https and now it is not firing AddEventListener function to invoke camera.

Does this library prevents calls coming from https? Do we need to make any change in the app handle https requests?
I also added NSAllowsArbitraryLoads = True flag in Info.plist
We really appreciate your help
Thanks

NullReferenceException in JsBridge.cs

Hi,

when I run your example project in the iPhone 5.1 simulator with MonoTouch, I get a null reference exception in JsBridge, line 269. Stepping in via the debugger, I can see "Client" is null.

I'm running:

MonoDevelop 3.0.3.2
Monotouch: 5.2.12
Mono 2.10.9 (tarball)
Xcode 4.3.2 (1177)
Mac OS X 10.7.4

Any ideas?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.