I'm trying to integrate google optimize on chrome extension using google tag manager. I have everything working right except for A/B testing:
here's the function I use to inject containers
const accountToken = `GTM-XXXXX`;
const googleOptimize = `OPT-XXXXX`;
const analyticsToken = `UA-XXXXXX-X`;
function integrateGTM() {
console.log("Trying GTM");
if (!document.querySelector("body")) {
return setTimeout(integrateGTM, 100);
}
const fliker = `
(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
})(window,document.documentElement,'async-hide','dataLayer',7000,
{'${accountToken}':true});`;
const gtm = `(function (w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({ "gtm.start": new Date().getTime(), event: "gtm.js" });
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != "dataLayer" ? "&l=" + l : "";
j.async = true;
j.src = "https://www.googletagmanager.com/gtm.js?id=" + i + dl;
console.log(j.src);
f.parentNode.insertBefore(j, f);
})(window, document, "script", "dataLayer", "${accountToken}");
`;
const analyticsSource = "https://www.google-analytics.com/analytics.js";
const analyticsCode = `
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '${analyticsToken}', 'auto');
ga('send', 'pageview');
`;
const optimizeSrc = `https://www.googleoptimize.com/optimize.js?id=${googleOptimize}`;
console.log(fliker, gtm);
const FLICKER = document.createElement("script");
FLICKER.async = false;
FLICKER.innerHTML = fliker;
document.querySelector("head").prepend(FLICKER);
const GTM = document.createElement("script");
GTM.innerHTML = gtm;
const sOPTIMIZE = document.createElement("script");
sOPTIMIZE.async = true;
sOPTIMIZE.src = optimizeSrc;
const analytics = document.createElement("script");
const analytics2 = document.createElement("script");
analytics.asyc = true;
analytics.src = analyticsSource;
analytics2.innerHTML = analyticsCode;
document.querySelector("head").append(GTM);
document.querySelector("head").append(analytics);
document.querySelector("head").append(analytics2);
document.querySelector("head").append(sOPTIMIZE);
const code = `<iframe src="https://www.googletagmanager.com/ns.html?id=${accountToken}"
height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
const bodyScript = document.createElement("noscript");
bodyScript.innerHTML = code;
document.body.prepend(bodyScript);
}
I even included the tools in the CSP:
"content_security_policy": "script-src 'self' https://www.google-analytics.com https://www.googletagmanager.com https://ajax.googleapis.com; object-src 'self'",
Yet each time I make a change, I get one of these errors in the variant debug mode:
Page modified after initial load
This experience was not applied.
This experience was activated in a previous event.
The following tags were blocked by Google Tag Manager from running on this page: esc.
Sometimes I don't even get any errors yet the experiment doesn't run!
I think this happening because the page changes its content because mainly the extension injects content to another website. I'm so lost.
Related
var json = [];
json.push(json2);
function makeallImage(){
console.log('json length'+json.length);
for (var v = 0; v < json.length; v++){
convertImgToBase64(v, "jpg");
console.log("ksana"+v);
}
}
function convertImgToBase64(number, outputFormat){
var tmpData =
canvas.loadFromJSON(json[number], canvas.renderAll.bind(canvas), function(){
**//need to absolute comfirm it add all object in canvas, load complete json2 //**
canvas.on('object:added', function(e) {
toImg();
});
});
}
function toImg(outputFormat){
var s = document.getElementById("last_Image");
var url = canvas.toDataURL();
var newImg = document.createElement("img"); // create img tag
console.log(newImg);
newImg.src = url;
newImg.width = 100;
newImg.height = 100;
s.appendChild(newImg);
console.log('mpike sto dom');
}
i am using this code to create image to field , problem is if my json object contain image ,it will create empty image. so i figure it out is because loading the src need time and canvas create image before it fully load.
i need to make sure the json fully loaded on canvas first , so i found a fabric code call object:added , which can make sure object added in canvas , but it count object one by one , so if my json cotain 2 object it will create more image.
achievement
1. i need to make sure my json fully load or create in canvas before create image , is they any way to make sure json fully added to canvas?
Demo see my problem using object:added it load multiple image.
You should dump reviver and use just the callback function.
http://jsfiddle.net/v1nmtz02/2/
You will have some difficulties with fabricImages and objects that have a content that is async. That is not yet solved at library level.
function _callback() {
canvas.renderAll();
toImg();
}
function convertImgToBase64(number, outputFormat){
var tmpData = canvas.loadFromJSON(json[number], _callback);
}
Complete snippet:
var canvas = new fabric.Canvas('canvas');
var json2 = '{"objects":[{"type":"circle","originX":"center","originY":"center","left":300,"top":400,"width":200,"height":200,"fill":"rgb(166,111,213)","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":{"color":"#5b238A","blur":20,"offsetX":-20,"offsetY":-10},"visible":true,"clipTo":null,"radius":100},{"type":"rect","originX":"center","originY":"center","left":300,"top":500,"width":150,"height":150,"fill":"#fbb802","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":{"color":"rgba(94, 128, 191, 0.5)","blur":5,"offsetX":10,"offsetY":10},"visible":true,"clipTo":null,"rx":0,"ry":0,"x":0,"y":0}],"background":""}';
var json = [];
json.push(json2);
function makeallImage(){
for (var v = 0; v < json.length; v++){
convertImgToBase64(v, "jpg");
}
}
function _callback() {
canvas.renderAll();
toImg();
}
function convertImgToBase64(number, outputFormat){
var tmpData = canvas.loadFromJSON(json[number], _callback);
}
function toImg(outputFormat){
var s = document.getElementById("last_Image");
var url = canvas.toDataURL();
var newImg = document.createElement("img");
newImg.src = url;
newImg.width = 100;
newImg.height = 100;
s.appendChild(newImg);
}
<script src="http://fabricjs.com/lib/fabric.js"></script>
<canvas id='canvas' width="550" height="550" style="border:#000 1px solid;"></canvas>
<button onclick="makeallImage();">makepng</button>
<div id="last_Image" style="background:red"></div>
how are you doing? I hope fine.
So I'm trying to send an urlRequest and I can't pass the parameters by url so I'm trying to use the URLVariable, but no matter what I try my php always get null.
var request:URLRequest = new URLRequest(SITE_DOMAIN + "/check_login.php");
request.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.login = emailInput.text;
variables.password = senhaInput.text;
variables.gotogame = "BURACO";
Reflect.setField(variables, "login", emailInput.text);
Reflect.setField(variables, "password", senhaInput.text);
Reflect.setField(variables, "gotogame", "BURACO");
request.data = variables;
request.method = URLRequestMethod.POST;
openfl.Lib.getURL(request);
As you guys can see I'm trying to set the variables in two ways but neither of they are working and I kind of don't know what to do anymore, please help.
Ive used this without problems:
var request:Http = new Http(SERVER + "actions/layout-builder?random=" + Math.random());
request.addParameter("action", "retrieve");
request.addParameter("layoutId", layoutId);
request.onError = function(msg) {
showSimplePopup("Problem loading layout:\n\n" + msg);
}
request.onStatus = function(status:Int) {
}
request.onData = function(response) {
response = StringTools.replace(response, "\r\n", "\n");
layoutCode.text = response;
}
request.request(false);
I'm using Node v0.10.11 on Ubuntu 12.04. I can't figure out what I'm missing to make streams of URLs work with the request module.
This program is trying to go to a mailing list site, find the download links for each month, then download the pages for each month.
Mikael's readme says "The first argument can be either an url or an options object. The only required option is URI, all others are optional.
uri || url - fully qualified uri or a parsed url object from url.parse()"
If I call url.parse(www.targeturl.com), I get
Error: options.uri is a required argument
If I don't use url.parse, I get
Error: Invalid URI "www.freelists.org/archive/si-list/06-2013"
(this link works perfectly fine in my browsers)
I've cut the code down to 42 lines. Any advice welcome
var request = require('request'),
url = require('url'),
stream = require('stream'),
cheerio = require('cheerio'), // a reduced jQuery style DOM library
Transform = require('stream').Transform
var DomStripStream = function(target) {
this.target = target;
stream.Transform.call(this,{objectMode: true});
}
DomStripStream.prototype = Object.create(
Transform.prototype, {constructor: {value: DomStripStream}}
)
DomStripStream.prototype.write = function () {
this._transform.apply(this, arguments);
};
DomStripStream.prototype.end = function () {
this._transform.apply(this, arguments);
this.emit("end");
};
DomStripStream.prototype._transform = function(chunk, encoding, callback) {
chunk = chunk ? chunk.toString() : "";
$ = cheerio.load(chunk);
domLinks = $(this.target);
$(domLinks).each(function (i, link) {
currLink = 'www.freelists.org' + $(link).attr('href')
// currLink = url.parse(currLink)
request(currLink, function (error, response, body) {
console.log(error);
})
});
}
var fs = require("fs"),
output = fs.createWriteStream("out.txt"),
mainPage = new DomStripStream('td a')
request('http://www.freelists.org/archive/si-list').
pipe(mainPage).
pipe(output);
add http:// or https:// in the url
I have a winJS app that is a working launcher for a steam game. I'd like to get it to cycle through 5 images even while not running.
It uses only the small tile — there are no wide tiles images for this app.
Here's the code:
(function () {
"use strict";
WinJS.Namespace.define("Steam", {
launch: function launch(url) {
var uri = new Windows.Foundation.Uri(url);
Windows.System.Launcher.launchUriAsync(uri).then(
function (success) {
if (success) {
// File launched
window.close();
} else {
// File launch failed
}
}
);
}
});
WinJS.Namespace.define("Tile", {
enqueue: function initialize() {
var updaterHandle = Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication();
updaterHandle.enableNotificationQueue(true);
return updaterHandle;
},
update: function update () {
var template = Windows.UI.Notifications.TileTemplateType.tileSquareImage;
var tileXml = Windows.UI.Notifications.TileUpdateManager.getTemplateContent(template);
var randIndx = Math.floor(Math.random() * 5);
var randUpdatetime = 1000 * 3 * (((randIndx == 0) ? 1 : 0) + 1); // let the base image stay longer
var tileImageAttributes = tileXml.getElementsByTagName("image");
tileImageAttributes[0].setAttribute("src", "ms-appx:///images/Borderlands2/borderlands_2_" + randIndx + "_sidyseven.png");
tileImageAttributes[0].setAttribute("alt", "Borderlands 2");
var tileNotification = new Windows.UI.Notifications.TileNotification(tileXml);
var currentTime = new Date();
tileNotification.expirationTime = new Date(currentTime.getTime() + randUpdatetime);
tileNotification.tag = "newTile";
var updater = Tile.enqueue();
updater.update(tileNotification);
setTimeout('Tile.update();', randUpdatetime);
}
});
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
setTimeout('Steam.launch("steam://rungameid/49520");', 800);
args.setPromise(WinJS.UI.processAll().then(function () {
return WinJS.Navigation.navigate("/default.html", args).then(function () {
Tile.update();
});
}));
}
};
app.start();
})();
Notes:
The code currently does not cycle the image, instead either
apparently never changing, or after launch replacing the application
name text with a tiny view of the default image. This reverts to the
text after a short time, and the cycle may repeat. It never shows a
different image (neither in the small image it erroneously shows, nor
in the main tile).
When I run in debug and set a breakpoint at the
TileUpdater.update(TileNotification) stage, I can verify in the
console that the image src attribute is set to a random image
just as I wanted:
>>>>tileNotification.content.getElementsByTagName("image")[0].getAttribute("src")
"ms-appx:///images/Borderlands2/borderlands_2_4_sidyseven.png"
But this never actually displays on the tile.
These image files are included in the solution, and they appear in the proper directory in the Solution Explorer.
If the image src attribute is set properly in debug then the image may not have the proper "Build Action".
In the 'Properties' of each image, set "Build Action" to "Resource".
I'm trying to display a simple playlist view in my Spotify app with the following code:
sp = getSpotifyApi(1);
var m = sp.require("sp://import/scripts/api/models");
var v = sp.require("sp://import/scripts/api/views");
var jq = sp.require('sp://XXX/jquery/jquery-1.7.1.min');
var pl = m.Playlist.fromURI('spotify:user:d3marcus:playlist:4zPZzImEYkUOVBvxIo42im');
var player = new v.Player();
player.track = pl.get(0);
player.context = pl;
var list = new v.List(pl);
$('XXX').append(list.node);
This will result in an empty list view and an error caught in sp://import/scripts/language.js:44: "Uncaught TypeError: Cannot read property 'length' of undefined"
Any suggestions?
I would say you are getting this error because the playlist has not yet loaded when you do pl.get(0). To make sure the playlist model has loaded you could either do
pl = m.Playlist.fromURI('spotify:user:d3marcus:playlist:4zPZzImEYkUOVBvxIo42im');
pl.observe(models.EVENT.LOAD, function() {
player.track = pl.get(0);
...
});
or
m.Playlist.fromURI("spotify:user:d3marcus:playlist:4zPZzImEYkUOVBvxIo42im", function(pl) {
player.track = pl.get(0);
...
});
I'm not sure, but could you try this :
$('YYY').append($(player.node));
$('XXX').append($(list.node));
instead of
$('XXX').append(list.node);
let us know...
For the 1.0 API:
require([
'$api/models',
'$views/list#List'
], function (models,List) {
var addList = function(list) {
list.load('tracks').done(function(list) {
list.tracks.snapshot().done(function(trackSnapshot){
// Make the playlist view
var multiple_tracks_player = document.getElementById('addedTracksList');
var playableList = List.forPlaylist(list);
multiple_tracks_player.appendChild(playableList.node);
playableList.init();
});
});
}
exports.addList = addList;
}
// Example of use:
addList(models.Playlist.fromURI(...))
I've tested it as used above, so it should work.
I found this in the tutorial-app available on github under "Playing music"-section -> "Play a list of tracks"
I hope this is helpfull.