Using Ezoic (or Adsense) with VueJS v2 - javascript

I have a new version of my site which uses VueJS v2 (the previous one didn't). The main code is placed inside <div id="app"></div> and Vue is initiated. The issue is that I partner with an advertising company called Ezoic that injects ads through using AI onto the page, but these ads aren't displaying properly. I believe it is related to these errors:
https://pagead2.googlesyndication.com/pagead/show_ads.js
show_ads.js:53 Failed to execute 'write' on 'Document': It isn't
possible to write into a document from an asynchronously-loaded
external script unless it is explicitly opened.
Ezoic works with Google Ad Exchange, so I believe it is the above line that's related to the issue.
I'm wondering, is there any way in which I could make my application compatible with Ezoic/Adsense? I thought about having Vue on the page only where needed, rather than the entire page (<div id="app"></div> goes from the start of body to the end of body), but this would mean I need multiple Vue instances running as I have components at the top (search box) and also throughout the pages.
I have no access to the code that Ezoic inject onto the page as this is done on their end (my site uses their DNS and they modify the response before sending to the visitor, to include the ad code). Ezoic team is also having a look into this issue presently but any information I could pass along could be helpful!

At the request of Dynamic Remo I am submitting an answer for Ezoic's standalone implementation that is compatible with Vue.
I will however preface this with they absolutely hate it when you install it this way and essentially refuse to support it. - with that said you have way more control over placement
The Solution:
First add the following script tag somewhere outside or your custom defined root element.
<script type="text/javascript" src="//www.ezojs.com/ezoic/sa.min.js" async=""></script>
In your vue component you will need to create all your placeholder elements with a id of "ezoic-pub-ad-placeholder-xx" where xx is replaced by the actual id found in your enzoic dashboard. Dynamic creation does work as long as there is a matching id in ezoic so you have two options:
Dynamic:
<div v-for="placeholderId in ezoicArray" :id="'ezoic-pub-ad-placeholder-' + placeholderId" class="ezoic"></div>
Standard:
<div id="ezoic-pub-ad-placeholder-102" class="ezoic"></div>
To actually display ads in your placeholders you can use this function I wrote. Just call it when the component is mounted.
ezoic(placeholderList) {
if (window.ezstandalone !== undefined) {
window.ezoicPlaceholderArray = window.ezoicPlaceholderArray || [];
// Add Placeholders to Array
placeholderList.forEach((placeholder) => {
this.addPlaceholderOnce(window.ezoicPlaceholderArray, placeholder);
});
// Enable Once - Refresh on Change
window.ezoicRefreshed = false;
window.ezoicEnabled = window.ezoicEnabled || false;
// Next Tick Ensures All Enzoic Blocks Are Loaded
this.$nextTick(() => {
// On First Load We Must Enable
if (!window.ezoicEnabled) {
window.ezstandalone.define(window.ezoicPlaceholderArray);
window.ezoicPlaceholderArray = null;
console.log('ezoic defined and array reset');
window.ezstandalone.enable();
console.log('ezoic enabled');
window.ezstandalone.display();
console.log('ezoic displayed');
window.ezoicEnabled = true;
window.ezoicRefreshed = true;
}
// On Refresh We Have To Destroy & Refresh
if (!window.ezoicRefreshed) {
window.ezstandalone.destroy();
console.log('ezoic destroyed');
window.ezstandalone.define(window.ezoicPlaceholderArray);
window.ezoicPlaceholderArray = null;
console.log('ezoic refresh defined and array reset');
window.ezstandalone.refresh();
console.log('ezoic refreshed');
window.ezoicRefreshed = true;
}
});
} else {
console.log('Error: Missing Ezoic Standalone');
}
},
addPlaceholderOnce(array, placeholder) {
if (!array.includes(placeholder)) {
array.push(parseInt(placeholder));
console.log('ezoic-pub-ad-placeholder-' + placeholder + ' - Created');
}
},
If you need to change your placeholder setup for different reasons as I do simply add window.ezoicRefreshed = false; to the appropriate lifecycle hook. In my case I have it in beforeUnmount because each route gets a custom placeholder list.
Hopefully this helps!

Related

My JSLink script will not work

I am attempting to use JSLink ..finally.. and I am having some trouble that I cannot seem to straighten out. For my first venture down the rabbit hole I chose something super simple for use as proof of concept. So I looked up a tutorial and came up with a simple script to draw a box around the Title field of each entry and style the text. I cannot get this to work. Is there any chance you can take a look at this code for me? I used the following tokens in the JSLink box.
~sitecollection/site/folder/folder/file.js
And
~site/folder/folder/file.js
The .js file is stored on the same site as the List View WebPart I am attempting to modify. The list only has the default “Title” column.
(function () {
var overrideContext = {};
overrideContext.Templates = {};
overrideContext.Templates.Item = overrideTemplate;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
}) ();
function overrideTemplate(ctx) {
return “<div style=’font-size:40px;border:solid 3px black;margin-bottom:6px;padding:4px;width:200px;’>” + ctx.CurrentItem.Title + “</div>”;
}
It looks as though you are attempting to override the context (ctx) item itself, where you actually just want to override the list field and the list view in which the field is displayed. Make sense?
Firstly, change overrideContext.Templates.Item to overrideContext.Templates.Fields :
(function () {
var overrideContext = {};
overrideContext.Templates = {};
overrideContext.Templates.Fields = {
// Add field and point it to your rendering function
"Title": { "View": overrideTemplate },
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
}) ();
Then when the JSLink runs the renderer looks for the Title field in the List view, and applies your overrideTemplate function.
function overrideTemplate(ctx) {
return “<div style=’font-size:40px;border:solid 3px black;margin-bottom:6px;padding:4px;width:200px;’>” + ctx.CurrentItem.Title + “</div>”;
}
In terms of running multiple JSLinks on a SharePoint page, it is quite possible to run multiple JSLink scripts, they just need to be separated by the pipe '|' symbol. I use SharePoint Online a lot and I see the following formatting working all the time (sorry Sascha!).
~site/yourassetfolder/yourfilename.js | ~site/yourassetfolder/anotherfilename.js
You can run as many scripts concurrently as you want, just keep separating them with the pipe. I've seen this on prem also, however you might want to swap out '~sites' for '~sitecollection' and make sure the js files you are accessing are at the top level site in the site collection if you do so!
I have noticed when running multiple JSLinks on a list or page because they are all doing Client Side Rendering, too many will slow your page down. If this happens, you might want to consider combining them into one JSLink script so that the server only has to call one file to return to the client to do all the rendering needed for your list.
Hope this helps.

When does the code in static/js/app.js in Phoenix get called?

These are some example code from the tutorial in Programming Phoenix book.
In web/static/js/video.js:
/***
* Excerpted from "Programming Phoenix",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt.
* We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/phoenix for more book information.
***/
let Video = {
init(socket, element){ if(!element){ return }
let playerId = element.getAttribute("data-player-id")
let videoId = element.getAttribute("data-id")
socket.connect()
Player.init(element.id, playerId, () => {
this.onReady(videoId, socket)
})
}
}
export default Video
In web/static/js/app.js:
import "phoenix_html"
import Video from "./video"
Video.init(socket, document.getElementById("video"))
video.js defines a Video object (Is that how I should call it?), which is imported in app.js, then app.js runs Video.init. If there's no DOM with #video the function will just return nothing.
I have two questions as to when that Video.init function gets called.
Is it automatically called when a page gets loaded? Is there another way to call it when I want to?
Is it called every time a page is loaded, regardless of which page I'm in?
Is it automatically called when a page gets loaded?
Is it called every time a page is loaded, regardless of which page I'm in?
The code will be called as soon as the module is included in the page, which, assuming you're using Brunch with Phoenix's default config, will be as soon as the execution reaches the end of app.js due to this line in Phoenix's default brunch-config.js:
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"]
}
},
So yes, it will be called on every page that includes js/app.js, which is all pages in Phoenix's default layout template.
Is there another way to call it when I want to?
Yes, you can call it from within web/static/js/app.js using Video.init() (like web/static/js/app.js is already doing). You can call it from another module by importing ./video, again just like web/static/js/app.js. You can e.g. attach it to an event being triggered, for example, when an element with id "foo" is clicked:
document.querySelector("#foo").addEventListener(function() {
Video.init(...)
});

storing a variable in localStorage is too slow

I have two jQuery mobile pages (#list and #show). There are several items on the #list page with different IDs. If I click on item no.5, the ID no5 will be stored in localStorage and I will be redirected to page #show
Now the problem:
Storing the ID in localStorage works, but the next page shows me not the item no.5, but it shows me an old item, that was in the localStorage before.
script from page #list
localStorage.setItem("garageID", $(this).attr('id'));
window.location.replace("#show");
I encountered this problem too (and not on a mobile : on Chromium/linux).
As there doesn't seem to be a callback based API, I "fixed" it with a timeout which "prevents" the page to be closed before the setItem action is done :
localStorage.setItem(name, value);
setTimeout(function(){
// change location
}, 50);
A timeout of 0 might be enough but as I didn't find any specification (it's probably in the realm of bugs) and the problem isn't consistently reproduced I didn't take any chance. If you want you might test in a loop :
function setLocalStorageAndLeave(name, value, newLocation){
value = value.toString(); // to prevent infinite loops
localStorage.setItem(name, value);
(function one(){
if (localStorage.getItem(name) === value) {
window.location = newLocation;
} else {
setTimeout(one, 30);
}
})();
}
But I don't see how the fact that localStorage.getItem returns the right value would guarantee it's really written in a permanent way as there's no specification of the interruptable behavior, I don't know if the following part of the spec can be legitimately interpreted as meaning the browser is allowed to forget about dumping on disk when it leaves the page :
This specification does not require that the above methods wait until
the data has been physically written to disk. Only consistency in what
different scripts accessing the same underlying list of key/value
pairs see is required.
In your precise case, a solution might be to simply scroll to the element with that given name to avoid changing page.
Note on the presumed bug :
I didn't find nor fill any bug report as I find it hard to reproduce. In the cases I observed on Chromium/linux it happened with the delete operation.
Disclaimer: This solution isn't official and only tested for demo, not for production.
You can pass data between pages using $.mobile.changePage("target", { data: "anything" });. However, it only works when target is a URL (aka single page model).
Nevertheless, you still can pass data between pages - even if you're using Multi-page model - but you need to retrieve it manually.
When page is changed, it goes through several stages, one of them is pagebeforechange. That event carries two objects event and data. The latter object holds all details related to the page you're moving from and the page you're going to.
Since $.mobile.changePage() would ignore passed parameters on Multi-page model, you need to push your own property into data.options object through $.mobile.changePage("#", { options }) and then retrieve it when pagebeforechange is triggered. This way you won't need localstorage nor will you need callbacks or setTimeout.
Step one:
Pass data upon changing page. Use a unique property in order not to conflict with jQM ones. I have used stuff.
/* jQM <= v1.3.2 */
$.mobile.changePage("#page", { stuff: "id-123" });
/* jQM >= v1.4.0 */
$.mobile.pageContainer.pagecontainer("change", "#page", { stuff: "id-123" });
Step two:
Retrieve data when pagebeforechange is triggered on the page you're moving to, in your case #show.
$(document).on("pagebeforechange", function (event, data) {
/* check if page to be shown is #show */
if (data.toPage[0].id == "show") {
/* retrieve .stuff from data.options object */
var stuff = data.options.stuff;
/* returns id-123 */
console.log(stuff);
}
});
Demo

Using Piwik for a Single Page Application

Building a single page / fat client application and I'm wondering what the best practice is for including and tracking using http://piwik.org/
I'd like to use Piwik in a way that is architecturally sound and replacable with a different library in the future.
It seems that there are two basic options for tracking with Piwik:
Fill up a global _paq array with commands, then load the script (it's unclear to me how to record future "page" views or change variables though)
Get and use var myTracker = Piwik.getTracker()
_paq approach:
myApp.loadAnalytics = function() { /* dynamically insert piwik.php script */ }
myApp.track = function(pageName) {
window._paq = window._paq || [];
_paq.push(['setDocumentTitle', pageName]);
_paq.push(["trackPageView"]);
}
myApp.loadAnalytics()
// Then, anywhere in the application, and as many times as I want (I hope :)
myApp.track('reports/eastWing') // Track a "page" change, lightbox event, or anything else
.getTracker() approach:
myApp.loadAnalytics = function() { /* dynamically insert piwik.php script */ }
myApp.track = function(pageName) {
myApp.tracker = myApp.tracker || Piwik.getTracker('https://mysite.com', 1);
myApp.tracker.trackPageView(pageName);
}
myApp.loadAnalytics()
// Then, anywhere in the application, and as many times as I want (I hope :)
myApp.track('reports/eastWing') // Track a "page" change, lightbox event, or anything else
Are these approaches functionally identical? Is one preferred over another for a single page app?
To have the tracking library used (eg. piwik) completely independent from your application, you would need to write a small class that will proxy the functions to the Piwik tracker. Later if you change from Piwik to XYZ you can simply update this proxy class rather than updating multiple files that do some tracking.
The Async code is a must for your app (for example a call to any 'track*' method will send the request)
The full solution using .getTracker looks like this:
https://gist.github.com/SimplGy/5349360
Still not sure if it would be better to use the _paq array instead.

Tridion 2011 SP1 : Tridion GUI Javascript error with Translation Manager and Powertools 2011 installed

I recently installed Tridion 2011 SP1 with SDL module Translation Manager enabled.
Everything was working fine. Then I installed the Tridion 2011 Powertools, following the installation procedure.
When trying to reload the GUI (browser cache emptied and modification parameter instanciated for server element in WebRoot\Configuration\System.Config) I'm getting the following Javascript error :
SCRIPT5007: Unable to get value of the property 'getItemType': object is null or undefined
Dashboard_v6.1.0.55920.18_.aspx?mode=js, line 528 character 851
And here is the concerned JS line:
Tridion.TranslationManager.Commands.Save.prototype._isAvailable=function(c,a){var
e=c.getItem(0),f=$models.getItem(e),b=f.getItemType(),d=$models.getItem(this.getTmUri ())
The preceding Javascript lines are dealing with other TranslationManager commands, so I suppose it is a kind of TranslationManager commands registration or somehting.
Trying to browse my Tridion publications by selecting any folder/strucutreGroup will also give the same error and the right frame (content frame) will not display any Tridion items but simply display:
Loading ...
Has anyone already experienced similar issue ?
For now I have no other choice than commenting out the Powertools sections file
Tridion_Home\web\WebUI\WebRoot\Configuration\System.Config
Thank you,
François
Strange thing here is that it refers to Save command which is not intended to be called or used from Dashboard.
I`d suggest to disable JS minification (JScriptMinifier filter in System.config), as it will probably show more correct details.
Another useful thing would be this error call stack.
--
I was not able to reproduce an issue from initial question, but had following error when I installed PT:
PowerTools is not defined
which appears in
*\PowerTools\Editor\PowerTools\Client\Shared\Scripts\ProgressDialog\ProgressDialog.js where it tries to register PowerToolsBase namespace, instead of PowerTools.
I`ll be surprised if adding
Type.registerNamespace("PowerTools");
at the top of the file will fix a problem, as in my case it was breaking entire GUI no matter if TM included or no.
I did check *\PowerTools\Editor\PowerTools\Client\Shared\Scripts\ProgressDialog\ProgressDialog.js, but the line
Type.registerNamespace("PowerTools");
was already there, so not the problem here.
Also, I disabled the JS minification. Here are the main methods the UI is loading before getting the error:
...
PowerTools.Commands.ItemCommenting.prototype.isValidSelection = function (selection) {
//Use the existing Save command from the CME
return $cme.getCommand("Save")._isEnabled(selection);
}
...
/**
* Executes this command on the selection.
* Override this method to implement the actual functionality.
* #param {Tridion.Core.Selection} selection The current selection.
*/
Tridion.TranslationManager.Commands.SendForTranslation.prototype._execute = function SendForTranslation$_execute(selection)
{
var selectedItems = selection.getItems();
if (selectedItems.length == 1)
{
var job = $models.getItem(selectedItems[0]);
if (job)
{
if (job.isLoaded())
{
job.saveAndSend();
}
else
{
$log.warn("Unable to send an unloaded job?! {0}".format(job.getId()));
}
}
else
{
$log.warn("Unable to execute save-and-send-for-translation for this selection: {0}".format(selectedItems));
}
}
else
{
$log.warn("Unable to save-and-send-for-translation multiple items at a time.");
}
};
...
Tridion.TranslationManager.Commands.Save.prototype._isAvailable = function Save$_isAvailable(selection, pipeline)
{
var itemUri = selection.getItem(0);
var item = $models.getItem(itemUri);
var itemType = item.getItemType(); !!!!!!!!! fails on this line !!!!!! item is null or not an object
var config = $models.getItem(this.getTmUri());
if (pipeline)
{
pipeline.stop = false;
}
if (config && config.hasChanged() && (itemType == $const.ItemType.CATEGORY || itemType == $const.ItemType.FOLDER || itemType == $const.ItemType.STRUCTURE_GROUP || itemType == $const.ItemType.PUBLICATION))
{
if (pipeline)
{
pipeline.stop = true;
}
return true;
}
return this.callBase("Tridion.Cme.Command", "_isAvailable", [selection, pipeline]);
};
Ok. It`s clear now.
PowerTools.Commands.ItemCommenting is used in Dashboard Toolbar.
This command uses Save to check its availability.
In the same time TM thinks that "Save" will only be used on an ItemToolbar.
The difference between this toolbars which cause an issue is that Dashboard view could have any-length selection, when Item view will always have selection having one item (currently opened).
Opening empty dashboard selection is not yet made, ItemCommenting tries to check its availability, by calling Save, which calls all its extensions. And so far as selection is empty
var itemUri = selection.getItem(0);
will return null, as well as
$models.getItem(null)
What you can do, is to remove ItemCommenting extension command as it is done in tridion powertool trunk editor.config.
http://code.google.com/p/tridion-2011-power-tools/source/browse/trunk/PowerTools.Editor/Configuration/editor.config?spec=svn942&r=903 [592]

Categories