简体   繁体   中英

Executing javascript code in background action on web application MVC

I have a script which basically looks like this:

<script>
// Send transaction data with a pageview if available
// when the page loads. Otherwise, use an event when the transaction
// data becomes available.
dataLayer.push({
  'ecommerce': {
    'purchase': {
      'actionField': {
        'id': 'T12345',                         // Transaction ID. Required for purchases and refunds.
        'affiliation': 'Online Store',
        'revenue': '35.43',                     // Total transaction value (incl. tax and shipping)
        'tax':'4.90',
        'shipping': '5.99',
        'coupon': 'SUMMER_SALE'
      },
      'products': [{                            // List of productFieldObjects.
        'name': 'Triblend Android T-Shirt',     // Name or ID is required.
        'id': '12345',
        'price': '15.25',
        'brand': 'Google',
        'category': 'Apparel',
        'variant': 'Gray',
        'quantity': 1,
        'coupon': ''                            // Optional fields may be omitted or set to empty string.
       },
       {
        'name': 'Donut Friday Scented T-Shirt',
        'id': '67890',
        'price': '33.75',
        'brand': 'Google',
        'category': 'Apparel',
        'variant': 'Black',
        'quantity': 1
       }]
    }
  }
});
</script>

Basically I need to execute this script in my code which will be triggered by a scheduled task every xx hour (probably every 4 hours).

The link to API:

https://developers.google.com/tag-manager/enhanced-ecommerce#purchases

The part that I'm interested in is:

Measuring Purchases

Basically since I couldn't find any sort of implementation for c# or PHP I decided to go this route with executing the javascript in the background...

What I thought it could look like:

private void ExecuteMyScript(){
// Now to execute the script above ...
}

This method would be triggered by the scheduled task every 4 hours.

Is this doable in .NET MVC? This is the first time I'm encountering something like this so all help and advice would be more than welcome.

Either you do the repetition from client side using Java Script's setInterval() . Example,

setInterval(
    function(){ 
        alert("Hello World"); // Replace this line with your code that you want to repeat every 3 seconds.
    }, 
    3000
);

Or you implement a scheduled task on your back end side and implement a publish subscribe pattern. Where your Java Script subscribes to the scheduled broadcast from your server with its callback function. There are many ways if you look for it and I do not know which to recommend as I haven't tried one myself. See SignalR, WebSockets and such for implementing "live"/"subscribable" api endpoints. I can only provide you a pseudo code below to tell the idea.

// C# backend part
namespace ScheduledTask
{
    public class NotificationTask
    {
        // Some kind of an event emitter class
        public Event notificationEvent; 
        // Some kind of Scheduler/Timer class library
        private ScheduleTimer scheduler;

        // Run()
        public void Run(IScheduledTask sheduledTask)
        {
            scheduler.start(timeout);
        }

        // timeout()
        private void timeout(data)
        {
            // emit event / notify
            notificationEvent.broadcast(data);
        }
    }
}


// JavaScript frontend part
// Subscribe to endpoint
api('/notification/id=1').subscribe(function(notification){
    // Do something with data received
});

This is of course possible and you have plenty of options... seeing that you are using ASP.NET MVC , I assume you are using Windows OS. You can create a Windows service and execute your scheduled job every 4 hours...

In case of my application (which also happens to an e-commerce website), I have written a windows Service using Topshelf which runs every 5 mins... but you don't have to use topshelf for writing a windows service, you can just create a Windows Service app

Depending on your hosting environment, you have other options... if your website is hosted on AWS, you can create an AWS Lambda function and configure the lambda function to run on a timely basis.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM