Rafael Nonino
Rafael Nonino

Reputation: 210

Flutter - Execute/Run Facebook Pixel Code(Javascript code) on Flutter App

I need to run a Javascript code in my Flutter app. When user press one button i need to run this code:

<!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '24023562411360');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=24035634111&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->

It is possible?

Now i'm trying this from flutter_webview_plugin, but i thinks isn't working:

flutterWebviewPlugin.evalJavascript(
          "<!-- Facebook Pixel Code --><script>!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window, document,'script','https://connect.facebook.net/en_US/fbevents.js');fbq('init', '24022385634361');fbq('track', 'PageView');</script><noscript><img height='1' width='1' style='display:none'src='https://www.facebook.com/tr?id=24022385634361&ev=PageView&noscript=1'/></noscript><!-- End Facebook Pixel Code -->");

Upvotes: 1

Views: 1562

Answers (2)

Matteo Antolini
Matteo Antolini

Reputation: 3068

To log events on Flutter Web, you firstly need to configure your Facebook Pixel inserting the snippet above </head> in web/index.html. You can find the snippet following this guide

After that, you can send events to your pixel utilizing dart interoperability. More informations here

import 'dart:developer';
import 'dart:js_interop_unsafe';
import 'dart:js_interop';

@JS()
external void fbq(String command, String eventName, JSAny? parameters);

class Tracking {
  static void sendEvent(
      {required String eventName, Map<String, dynamic>? parameters}) {
    //Meta Pixel
    try {
      final args = parameters?.jsify();
      fbq('trackCustom', eventName, args);
    } catch (e) {
      log(e.toString());
    }
  }
}

Upvotes: 0

MαπμQμαπkγVπ.0
MαπμQμαπkγVπ.0

Reputation: 6737

AFAIK, there are plugins currently available to call a js function. See examples from the following plugins:

Check out this blog "JavaScript with Flutter | Is it possible?" to give you guide on implementation of js inside your Flutter app.

Upvotes: 1

Related Questions