How do I call AdSense Auto Ads on route change for SPA (single page app)? - adsense

I have included the needed script tag in the global template.html file which contains all dynamic pages for my SPA (written in Sapper/Svelte).
www.ensueco.com
<script data-ad-client="ca-pub-XXXXXXXXXXXXXXXX" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
​If I load the index page, auto ads load perfectly, but when I click a link navigating to another page/article, client-side routing will change the content in the content window, but won't recreate new autogenerated ads.
If I open a given article/subpage as initial page load, it also loads ads from auto ads perfectly, but clicking "home" in main navigation going back to the homepage, doesn't load new ads in the content window.
Q: How do I ask the adsbygoogle script to execute again on client-side routing to fill in auto ads on all pages?
I currently have a script that subscribes to route change events and forward these informations to Google Analytics:
page.subscribe(({ path, params, query }) => {
gtag("config", "GOOGLE_ANALYTICS", { page_path: path });
});
But not sure if I could do something similar in this to ask adsbygoogle to execute again? (below code has been tested and doesn't work)
page.subscribe(({ path, params, query }) => {
// (window.adsbygoogle = []).push({
// google_ad_client: "ca-pub-XXXXXXXXXXXXX",
// enable_page_level_ads: true,
// tag_partner: "site_kit"
// });
gtag("config", "GOOGLE_ANALYTICS", { page_path: path });
});
Above code at testing gives me this:
I get this error on route change then:
Uncaught
O {message: "adsbygoogle.push() error: Only one 'enable_page_level_ads' allowed per page.", name: "TagError", pbr: true, stack: "TagError: adsbygoogle.push() error: Only one 'enab…esyndication.com/pagead/js/adsbygoogle.js:58:409)"}
And if I remove the enable_page_level_ads I get this:
Uncaught
O {message: "adsbygoogle.push() error: All ins elements in the … with class=adsbygoogle already have ads in them.", name: "TagError", pbr: true, stack: "TagError: adsbygoogle.push() error: All ins elemen…js/adsbygoogle.js:185:25)↵ at <anonymous>:1:38"}
So basically, I need to execute some method that creates new tags (based on auto ads) so I can execute this method and populate all the new ins elements. I think.
Thanks
ADDITIONAL THOUGHTS
From what I understand, the script is loaded post SSR (server-side rendering), why the content, HTML, CSS, and JS from my site already is loaded once the adsbygoogle script is executed.
From a development POW, I would expect it to be possible to empty the adsbygoogle array and re-initialize the ads by google script in order for the JS, to crawl the now dynamically loaded content and based on the new window.pushed URI (window.history.pushState()), and place new ads as it would have done anyway, should it have been loaded after this particular page's SSR.

Possible Solution with jQuery
Make a file:
If you place the script tag in a separate php/html file call it autoads.html and place you ads script tag inside it. Place this somewhere you can call it from on the server via URL.
<script data-ad-client="ca-pub-XXXXXXXXXXXXXXXX" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
Call the file:
Using jQuery .click & .load functions we can call the autoads.html via it's URL when a link with the class .myNavButton is clicked which should execute any scripts which the file contains.
As the script isn't visible we can just load it into the body tag, although any existing tag should work.
HTML
Home
Some Page
Another Page
jQuery
$(document).ready(function(){
$(".myNavButton").click(function(){
$("body").load("autoads.html");
});
});
Alternative:
As executing the script multiple times could cause conflict issues an alternative might be target the jQuery to reload any iframes on the page.
Maybe using something like this inside the click function?
$('iframe').attr('src', $('iframe').attr('src'));
Sources:
https://www.w3schools.com/jquery/ajax_load.asp
https://api.jquery.com/load/
https://css-tricks.com/snippets/jquery/force-iframe-to-reload/

Related

POST to Salesforce API using Google Tag Manager and JSforce not working?

I want to use Google Tag Manager to send data to our Salesforce org for certain events on our website (user signup, conversion etc). After some research, I realized JSforce would be the easiest way to achieve this. I created a new connected app in Salesforce, tried out the Salesforce API using Postman and successfully managed to create a new user account via the API. Then I moved on to try and achieve the same thing in Google Tag Manager. I read JSforce's docs and attempted to implement everything. But, after multiple hours of troubleshooting and Google searching, I can't seem to make it work.
Here is my current code, which is in a 'tag' in Google Tag Manager that triggers on all pages (just for testing):
https://jsforce.github.io/start/#web-browser
<script src="//cdnjs.cloudflare.com/ajax/libs/jsforce/1.9.1/jsforce.min.js"></script>
<script>
jsforce.browser.init({
clientId: '<MYCLIENTID>',
redirectUri: 'https://cuttersclub.com'
});
https://jsforce.github.io/document/#access-token
var jsforce = require('jsforce');
var conn = new jsforce.Connection({
instanceUrl : 'https://um5.salesforce.com',
accessToken : '<MYACCESSTOKEN>',
});
https://jsforce.github.io/document/#create
conn.sobject("Account").create({ Name : 'My Account #1' }, function(err, ret) {
if (err || !ret.success) { return console.error(err, ret); }
console.log("Created record id : " + ret.id);
});
</script>
I'm getting this error in the browser console:
Uncaught ReferenceError: require is not defined
EDIT: Removing var jsforce = require('jsforce'); solved this problem and accounts are being created in Salesforce. But, now I am getting the following error in the browser console:
Access to XMLHttpRequest at '<URL>' from origin '<CALLBACKURL>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
As mentioned in the JSforce docs, I think it may be something to do with proxy servers: https://github.com/jsforce/jsforce-ajax-proxy
I don't know that much about salesforce, but "require" is something from node.js, not a function that is implemented in the browser.
If I understand the documentation correctly, then for a browser project it should be enough to call the jsforce script via a script tag. You should not need any way to "require" files after that, since the jsforce script already contains everything you need. So you should be fine if you just remove the offending lines (i.e. all references to "require('jsforce');").

Facebook share to refer back traffic to the iframe page tab

SO here's what I am after. I have a FB page tab that runs the content of the site https://site.com/
I set up a FB share link to share a page aboutus.html. When I share it FB allows me to share this URL https://site.com/aboutus.html, but how can i send the traffic directly to the iFrame on the page tab? For example https://www.facebook.com/fan_page/app_331267943480920398/whatever_aboutus.html
I know it is possible because I saw it one day - cant remember now where.
Thanks.
You can't pass in filenames this way, that's only supported on Canvas Apps.
The best workaround to replicate this is using the app_data parameter. Basically, have your landing page (as defined in your app settings), be some kind of server side script which listens to the Signed Request, specifically the app_data parameter. Then you have that script load content based on the contents of that.
So as an example, let's imagine I want to load http://mybasedomain.com/foo.php or http://mybasedomain.com/bar.php. I direct users to https://www.facebook.com/PAGENAME/app_APPID?app_data=foo or https://www.facebook.com/PAGENAME/app_APPID?app_data=bar, then on my landing page, I have a simple if/else statement to parse that and render the relevant content -
<?php
// Assumes you have this parse_signed_request function - https://gist.github.com/872837
// And a $config array, which contains your app_secret
$signed_request = parse_signed_request($_REQUEST['signed_request'], $config['AppSecret']);
if ($signed_request['app_data'] === 'foo') {
include('foo.html');
} else if ($signed_request['app_data'] === 'bar') {
include('bar.html');
} else {
include('index.html');
}

Passing Parameters from e-mail link to jQuery mobile web app

I created a web app using jquery mobile 1.1.1
As part of my app I built password retrieval functionality. If a user needs to reset their password, they fill out a form and receive an e-mail with a link that includes the address of the password reset page and two other parameters as such:
www.mywebapp.com/demo.html#resetPassword?x=123&y=123
The Initial Problem:
When the user clicks on the link, they see the home page of the web app even though the URL in the address bar says: www.mywebapp.com/demo.html#resetPassword?x=123&y=123 I understand that jQuery mobile does not support passing parameters after the hash, so I came up with the following solution.
A Solution with a small inconvenience:
I put together the following code, which reads the URL, captures my two parameters and redirects the user to the password reset page:
$( document ).bind( "pagebeforeshow", function() {
//cpe("parameter") will check whether the specified URL parameter exists
if(cpe("x") && cpe("y")){
//gpv("parameter") captures the value of the specified URL parameter
recovery.username=gpv("x");
recovery.token=gpv("y");
$.mobile.changePage("#resetPassword");
}
})
The Inconvenience, and thus my current problem:
When the user clicks on the link in the e-mail the browser fires up and opens the main page of the app, and then it quickly displays the #resetPassword page. I understand that this happens because I'm changing the page
$.mobile.changePage("#resetPassword");
But, how do I modify the above code so that the user won't see the main page at all, and go straight to the #resetPassword page?
Use an empty initial page with no content. By default do a changePage to what was your initial page, but in other cases, like the resetPassword case, you changePage to that instead.
I followed Raymond Camden's suggestion and added the following to my html:
<pre>
<!--Start of blank initial page: #initPage-->
<div data-role="page" id="initPage">
<div data-role="content"></div>
</div>
<!-- /page -->
</pre>
I also added the following to my javascript:
//init page -> path control hub
$( document ).bind( "pagebeforeshow", function() {
var pageid=$.mobile.activePage.attr('id');
if(pageid=="initPage"){
if(cpe("x") && cpe("y")){
recovery.username=gpv("x");
recovery.token=gpv("y");
$.mobile.changePage("#resetPassword");
}else{
$.mobile.changePage("#info");
}
}
})
It's working now.

Set up facebook UrchinTracker for aJax calls for Google Analytics

I have set up the Google Analytics in my FBML facebook application. It works for tracking the php pages. (I can see the report in GA).
However, I also want to track the aJax calls, because most of the pages of my application is ajax driven, rather than loading differnet php pages.
so, that's what I put in the code (before ajax call)
Facebook.urchinTracker('/importantpage/');
THere is no error return when running the application.
However, when I look at the Google Analytics, I can't find any report showing this is being tracked. I look at the Event tracking.. nothing. I look at the overview, it only shows the php pages statistic.
So, where should I look in Google Analytics? and do I need to set up anything in GA for tracking the ajax call for 'importantpage' ?
try calling urchin within you AJAX function. Like :
function callPage(div,params, page)
{
Facebook.urchinTracker(page);
var ajax_content = new Ajax();
ajax_content.responseType = Ajax.FBML;
ajax_content.ondone = function(data)
{
document.getElementById(div).setInnerFBML(data);
}
var params={"Params":params,"target":div};
ajax_content.post(page,params);
}

Google Chrome Extension - Accessing The DOM

I have been searching around the web to find out how to access the current tabs DOM to extract information out of a page from the background.html. So far I have had no luck, or at least nothing I could get to work properly.
To state the problem simply. I would like to get src of a iFrame on the page. Any Suggestions?
One way, you an treat this as a single one time request to the content-script which will fetch the dom you want to access.
http://code.google.com/chrome/extensions/messaging.html#simple
Basically, your content script sets up the listener:
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
else
sendResponse({}); // snub them.
});
And your background page sends a single lived request:
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
When you send your response, you send it as JSON data, you can fetch whatever you want (such as html, dom, text, etc).
That is currently the only way to let the background page know anything about the contents of a page. Remember you would need content scripts and tab permissions.