clevertap event not trigger in javascript - javascript

I have to create subscribe and unsubscribe email page. all functionality is working fine. but when I call clevertap event, CT event is not triggered in CT dashboard.
<script type="text/javascript">
var clevertap = {
event: [],
profile: [],
account: [],
onUserLogin: [],
notifications: [],
privacy: [],
};
// replace with the CLEVERTAP_ACCOUNT_ID with the actual ACCOUNT ID value from your Dashboard -> Settings page
clevertap.account.push({ id: "TEST-000-000-001Z" });
clevertap.privacy.push({ optOut: false });
clevertap.privacy.push({ useIP: true });
(function () {
var wzrk = document.createElement("script");
wzrk.type = "text/javascript";
wzrk.async = true;
wzrk.test = 'page';
wzrk.src =
("https:" == document.location.protocol
? "https://d2r1yp2w7bby2u.cloudfront.net"
: "http://static.clevertap.com") + "/js/a.js";
var s = document.getElementsByTagName("script")[0];
console.log('s.parentNode : ', s.parentNode)
s.parentNode.insertBefore(wzrk, s);
wzrk.onerror = (e) => reject(new Error(`Failed to load script '${src}'. Error: ${e.toString()}`));
})();
</script>
onload I have call page view event
<script>
window.onload = function () {
console.log('on load');
var isReEncode = false; //Should be true only if your server is url encoding the URL on unsubscribe landing page
var withGroups = true; // Should be true if the unsubscribe groups should be displayed on the landing page.
var stageName;
$WZRK_WR.getEmail(false, withGroups);
showSectionBaseOnStage();
setTimeout(() => {
clevertap.event.push("Page viewed", {
"ProductName": "ABC",
"PageTitle": "Unsubscribe",
"Page": 'Group Unsubscribe',
"PageURL": window.location.href,
"SourceURL":""
});
console.log("on load ct event call", clevertap);
}, 5000);
};
</script>
Page viewed event not trigger
Please let me know where I do a mistake.
Thank you

Related

How to call a function which defined in external script in react

I am new to reactjs.
I am trying to add a external script and trying to use a function which defined inside that script.
Script is
<script src="https://pi-test.sagepay.com/api/v1/js/sagepay.js"></script>
<script>
document.querySelector('[type=submit]').addEventListener(
'click',
function (e) {
e.preventDefault(); // to prevent form submission
sagepayOwnForm({
merchantSessionKey: '5528D329-A83B-435F-B6A7-E38A2BC60DC9',
}).tokeniseCardDetails({
cardDetails: {
cardholderName: document.querySelector(
'[data-card-details="cardholder-name"]'
).value,
cardNumber: document.querySelector(
'[data-card-details="card-number"]'
).value,
expiryDate: document.querySelector(
'[data-card-details="expiry-date"]'
).value,
securityCode: document.querySelector(
'[data-card-details="security-code"]'
).value,
},
onTokenised: function (result) {
if (result.success) {
document.querySelector('[name="card-identifier"]').value =
result.cardIdentifier;
document.querySelector('form').submit();
} else {
alert(JSON.stringify(result));
}
},
});
},
false
);
</script>
I tried with useScript. When user click the submit button the script will loaded and should call
sagepayOwnForm ( this is a defined in their script.js)
I create a useScript
export const useScript = (url: string) => {
useEffect(() => {
const script = document.createElement('script');
script.src = url;
script.async = true;
// script.on
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, [url]);
};
I don't know how to use this. I want to know How can I call their function.
Can anyone help me.

criteo tags on ajax site

I have an issue with integrating criteo tags into my ajax website.
Everything works perfectly when I send my first event.
<script type="text/javascript" src="//static.criteo.net/js/ld/ld.js" async="true"></script>
<script type="text/javascript">
window.criteo_q = window.criteo_q || [];
window.criteo_q.push(event_data);
</script>
But when I try to send another event into criteo without page reload it does not work. Event does not appear in criteo.
<script>
window.criteo_q.push(event_data);
</script>
Any ideas what is wrong?
Demo example: of https://jsfiddle.net/36jq9dLu/156/
You should programmatically reimport the loader every time you want to fire a new event. This won't cause any latency as the loader is cached by the browser, but is necessary as it contains some code useful to reinitialize the criteo_q object. You can add the following lines before every event fire:
window.criteo_q = undefined;
script = document.createElement('script');
script.src = '//static.criteo.net/js/ld/ld.js';
script.async = 'true'
document.head.appendChild(script);
window.criteo_q = window.criteo_q || [];
https://jsfiddle.net/36jq9dLu/199/
In order for Criteo OneTag to properly evaluate events after DOM-change you should set widget to non-blocking mode by using requiresDOM parameter.
...
events = [
{ event: 'setAccount', account: 123456 },
{ event: 'setHashedEmail', email: '1234567890asdf' },
{ event: 'setSiteType', type: 'd' },
{ event: 'viewHome' },
{ requiresDOM: "non-blocking", cb:
$(document.body).on("page:changed", function() {
product_event =
[
{ event: 'setAccount', account: 123456 },
{ event: 'setHashedEmail', email: '1234567890asdf' },
{ event: 'setSiteType', type: 'd' },
{ event: "viewItem", product: 123 }
]
criteo_q.push(product_event)
})
}
]
window.criteo_q.push(events);
...
Following snippet demonstrates this:
https://jsfiddle.net/yuxqrfev/5/

My IndexedDB add() in my service worker succeed but I cannot see the data it in the Chrome dev tools Application/Storage

I am on Chrome Version 57.0.2987.110 (64-bit) on MacOS/OSX 12.3 Sierra,
I managed to get a service worker working, but I must say I am new at this.
I now try to get it to use an IndexedDB and store data in it.
It fetches data from a local web server in http and retrieve it without problem in json format.
The data format is :
[{"id":"1", "...":"...", ...},
{"id":"2", "...":"...", ...},
{"id":"3", "...":"...", ...},
...
{"id":"n", "...":"...", ...}]
it then adds the data to an IndexedDB without problem apparently because the onsuccess callback is triggered ...
entityObjectStore.add success : Event {isTrusted: true, type: "success", target: IDBRequest, currentTarget: IDBRequest, eventPhase: 2…}
But it does not appear in the Chrome dev tools!
Here is my service worker:
self.addEventListener('install',function(event)
{
event.waitUntil(
(new Promise(function(resolve,reject)resolve()}))
.then(function()
{return self.skipWaiting();}));
});
self.addEventListener('activate', function(event)
{
event.waitUntil(
(new Promise(function(resolve,reject){resolve()}))
.then(function() {return self.clients.claim();}));
});
self.addEventListener('message', function(event)
{
if(event.data.command=="data.load")
{
var options = event.data.options
var url = new URL(event.data.host+options.source);
var parameters = {entity:options.name,
options:encodeURIComponent(options.options)};
Object.keys(parameters)
.forEach(key => url.searchParams.append(key,
parameters[key]))
fetch(url).then(function(response)
{
if(response.ok)
{
response.json().then(function(data_json)
{
var entityData = data_json;
var request = indexedDB.open(options.name);
request.onerror = function(event)
{
console.log("indexedDB.open error :",event);
};
request.onsuccess = function(event)
{
console.log("indexedDB.open success :",event)
var db = event.target.result;
}
request.onupgradeneeded = function(event)
{
console.log("indexedDB.open upgrade :",event)
var db = event.target.result;
db.createObjectStore(options.options.id, { keyPath: "id" });
objectStore.transaction.oncomplete = function(event)
{
var entityObjectStore = db.transaction(options.options.id, "readwrite").objectStore(options.options.id);
for (var i in entityData)
{
var addRequest = entityObjectStore.add(entityData[i]);
addRequest.onerror = function(event)
{
console.log("entityObjectStore.add error :",event);
};
addRequest.onsuccess = function(event)
{
console.log("entityObjectStore.add success :",event);
};
}
}
};
});
}
});
}
else if(event.data.command=="data.get")
{
var command = event.data;
var request = indexedDB.open(command.domain);
request.onerror = function(event)
{
console.log("indexedDB.open error :",event);
};
request.onsuccess = function(event)
{
console.log("indexedDB.open success :", event)
var db = event.target.result;
var transaction = db.transaction([command.domain]);
var objectStore = transaction.objectStore(command.entity);
var request = objectStore.get(command.id);
request.onerror = function(event)
{
console.log("objectStore.get error :",event);
};
request.onsuccess = function(event)
{
console.log("objectStore.get success :",event);
console.log("request.result=" + request.result);
};
}
}
});
Here is the HTML file I use with it :
<!DOCTYPE html>
<html>
<head>
<title>My service worker app</title>
</head>
<body>
<button id="update">Update</button>
<div id="log"></div>
<script type="text/javascript">
function sendMessage(message)
{
return new Promise(function(resolve, reject)
{
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(event)
{
if (event.data.error)
{
reject(event.data.error);
}
else
{
resolve(event.data);
}
};
});
}
if (navigator.serviceWorker.controller)
{
var url = navigator.serviceWorker.controller.scriptURL;
var initData = [
{
name:"my_entity_type",
source:"/webapp/data",
options:{id:"my_entity_type_id"}
}
]
for(var dataIndex in initData)
{
var data = initData[dataIndex]
sendMessage({
command:"data.load",
host: document.location.origin,
options: data
});
}
}
else
{
navigator.serviceWorker.register('/webapp/lt_sw.js')
.then(function(registration)
{
debug('Refresh to allow ServiceWorker to control this client', 'onload');
debug(registration.scope, 'register');
});
}
navigator.serviceWorker.addEventListener('controllerchange',
function()
{
var scriptURL = navigator.serviceWorker.controller.scriptURL;
debug(scriptURL, 'oncontrollerchange');
});
document.querySelector('#update').addEventListener('click',
function()
{
navigator.serviceWorker.ready.then(function(registration)
{
registration.update()
.then(function()
{
console.log('Checked for update');
})
.catch(function(error)
{
console.error('Update failed', error);
});
});
});
function debug(message, element)
{
var target = document.querySelector('#log');
console.log(element,":",message)
target.textContent = message;
}
</script>
</body>
</html>
Any idea about what I am, doing wrong?
Edit 1:
I modified the script in the html file so that update mechanism sends another message to the service worker asking for data :
document.querySelector('#update').addEventListener('click',
function()
{
navigator.serviceWorker.ready.then(function(registration)
{
registration.update()
.then(function()
{
console.log('Checked for update');
sendMessage({
command:"data.get",
domain:"database_name",
entity: "my_entity_type",
id: "my_entity_id"
});
})
.catch(function(error)
{
console.error('Update failed', error);
});
});
});
And I added the following line:
indexedDB.webkitGetDatabaseNames().onsuccess = function(sender,args){ console.log("data.get all dbs:",sender.target.result); };
Just at the beginning of the data look up part:
else if(event.data.command=="data.get")
{
To list all the IndexedDBs on Chrome as explained here : https://stackoverflow.com/a/15234833/2360577
And I get all the databases I created previously!
data.get all dbs: DOMStringList {0: "db1", 1: "db2", 2: "db3", 3: "db4", length: 4}
Then I proceeded to list all ObjectStores in these dbs, also as explained in the previous link, by adding the following line :
indexedDB.open(<databaseName>).onsuccess = function(sender,args)
{"<databaseName>'s object stores",console.log(sender.target.result.objectStoreNames); };
And apart for one, where the data is processed and apparently does not work, they all had one object store with the same name as the db that contains it as expected ...
db1's object stores DOMStringList {0: "db1", length: 1}
db2's object stores DOMStringList {length: 0}
db3's object stores DOMStringList {0: "db3", length: 1}
db4's object stores DOMStringList {0: "db4", length: 1}
Then I had a look inside the object stores ...
indexedDB.open("db3").onsuccess = function(event)
{event.target.result.transaction(["db3"]).objectStore("db3")
.getAll().onsuccess = function(event)
{console.log("objectStore.getAll() success :",event.target.result)};};
And the entries are there as expected! But not in Application/Storage ...
Edit 2:
The error for db2 was apparently that I did not refresh the data in the database ... this part works now ...
Edit 3:
The answer was as simple as closing and reopening the dev tools ... like #wOxxOm suggested ...
It works for me if I close DevTools and open again. Did you try that?
You could also check the "Update on reload" button and try hard reset ctrl/shift+f5 to the same effect as #wOxxOm mentioned.

Firefox Extension trouble using port.emit and port.on

I can't seem to get port.emit working correctly with my Firefox extension. From the init() function in popup.js the messages are correctly sent to main.js using addon.port.emit. Once they've been sent, the giveStorage message is correctly received in popup.js. However, this only works correctly when the original message is sent in the init function.
When I try sending the messages using using the jQuery change listener, the logs "Storage has been set." and "Sending storage to popup.js" come through, so popup.js is just not receiving it, but I have no idea why not. Only messages are logged correctly when ran from the init function.
If anyone has any ideas, or if you need any more information, please let me know and I'll see what I can do. Any help is greatly appreciated!
main.js
panel.port.on("setStorage", function (text) {
console.log("Storage has been set.");
ss.storage[text[0]] = text[1];
})
panel.port.on("getStorage", function (text) {
console.log("Sending storage to popup.js");
panel.port.emit("giveStorage", [text, ss.storage[text]])
})
popup.js
function init(){
$(".panel").hide();
addon.port.emit("getStorage", "username");
addon.port.emit("getStorage", "volume");
setInterval(function(){following();}, 60000);
}
addon.port.on("giveStorage", function (text) {
console.log("Message received from main.js");
if (text[1] !== null) {
if (text[0] === "username") {
username = text[1];
$('#menuFollowing').click();
}
else if (text[0] === "volume"){
volume = text[1];
$("#volume").val(volume);
$('#volumeValue').empty();
$('#volumeValue').append('Volume: ' + volume);
}
}
})
$('#volume').change(function(){
volume = $('#volume').val();
addon.port.emit("setStorage", ["volume", volume]);
addon.port.emit("getStorage", "volume");
});
Complete main.js
var { ToggleButton } = require('sdk/ui/button/toggle');
var panels = require("sdk/panel");
var self = require("sdk/self");
var ss = require("sdk/simple-storage");
var notifications = require("sdk/notifications");
var panel = panels.Panel({
width: 500,
height: 500,
contentURL: self.data.url("popup.html"),
onHide: handleHide,
});
var button = ToggleButton({
id: "hitbox-plus",
label: "hitbox Plus",
icon: {
"16": "./icon16.png",
"48": "./icon48.png",
},
onChange: handleChange,
});
function handleChange(state) {
panel.contentURL = self.data.url("popup.html");
if (state.checked) {
panel.show({
position: button
});
}
}
function handleHide() {
button.state('window', {checked: false});
}
panel.port.on("getStorage", function (text) {
console.log("Sending storage to popup.js");
panel.port.emit("giveStorage", [text, ss.storage[text]])
})
panel.port.on("setStorage", function (text) {
console.log("Storage has been set.");
ss.storage[text[0]] = text[1];
})

Backbone JS automatically routing back to default

I've just started foundational work for a Backbone JS SPA (single page application). I'm using the basic Underscore templating support, and am having issues with unexpected routing occurring.
Basically, the sign up view is shown initially as expected, POSTs succesfully when I click a button and I have it navigate to a simple test view. However, the test view is quickly rendered and then I get re-routed to the default sign up view again.
I see the history of the test page and if I hit the back button I go back to that test view which works fine. I see there is some event being triggered in Backbone which is routing me back to the blank fragment (sign up page), but I have no idea why. I've tried messing with the replace and trigger options on the navigate call with no luck.
As a side note, the start() and stop() View functions were adapted from this article: http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/ . I tried removing this and it had no effect.
$(document).ready( function(){
Backbone.View.prototype.start = function() {
console.debug('starting');
if (this.model && this.modelEvents) {
_.each(this.modelEvents,
function(functionName, event) {
this.model.bind(event, this[functionName], this);
}, this);
}
console.debug('started');
return this;
};
Backbone.View.prototype.stop = function() {
console.debug('stopping');
if (this.model && this.modelEvents) {
_.each(this.modelEvents,
function(functionName, event) {
this.model.unbind(event, this[functionName]);
}, this);
}
console.debug('stopped');
return this;
};
var myApp = {};
myApp.SignUp = Backbone.Model.extend({
urlRoot:"rest/v1/user",
defaults: {
emailAddress: "email#me.com",
firstName: "First Name",
lastName: "Last Name",
password: "",
confirmPassword: ""
}
});
myApp.SignUpView = Backbone.View.extend({
el: $('#bodyTarget'),
modelEvents: {
'change' : 'render'
},
render: function(){
document.title = "Sign Up Page";
// Compile the template using underscore
var template = _.template( $("#signUpTemplate").html(), this.model.toJSON());
// Load the compiled HTML into the Backbone "el"
this.$el.html( template );
return this;
},
events: {
"click .signUpButton": "signUp"
},
signUp: function() {
bindFormValues(this);
this.model.save(this.model.attributes, {error: this.signUpFailure});
myApp.router.navigate("test", {trigger: true});
},
signUpFailure: function(model, response) {
alert("Failure: " + response);
}
});
myApp.TestView = Backbone.View.extend({
el: $('#bodyTarget'),
modelEvents: {
'change' : 'render'
},
render: function() {
document.title = "Test Page";
this.$el.html( "<div>this is a test view</div>");
return this;
}
});
// for now, just pull values from form back into model
function bindFormValues(view) {
var mod = view.model;
var el = view.$el;
var updates = {};
for (var prop in mod.attributes) {
var found = el.find('* [name="' + prop + '"]');
if (found.length > 0) {
updates[prop] = found.val();
}
}
mod.set(updates/*, {error: errorHandler}*/);
}
// routers
myApp.Router = Backbone.Router.extend({
routes: {
'test': 'test',
'': 'home',
},
home: function() {
console.debug('home:enter');
this.signUpView = new myApp.SignUpView({model: new myApp.SignUp()});
this.showView(this.signUpView);
console.debug('home:exit');
},
test: function() {
console.debug('test:enter');
this.testView = new myApp.TestView({model: new myApp.SignUp()});
this.showView(this.testView);
console.debug('test:exit');
},
showView: function(view) {
if (this.currentView) {
this.currentView.stop();
}
this.currentView = view.start().render();
}
});
myApp.router = new myApp.Router();
Backbone.history.start();
});
My HTML page just brings in the relevant scripts and has the div element bodyTarget which is injected with the views when it loads.
Edit: Duh, I found the problem. It turns out I needed to prevent event propagation on the call to signUp() by returning false.

Categories

Resources