how to use Postmedia digital cordova plugin (DFP) - javascript

I would like to use DFP (double click for Plublisher) for my android app, I already have the generated scripts and markup as below:
<script type='text/javascript'>
(function() {
var useSSL = 'https:' == document.location.protocol;
var src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
document.write('<scr' + 'ipt src="' + src + '"></scr' + 'ipt>');
})();
</script>
<script type='text/javascript'>
googletag.defineSlot('/*****/****_APP_1024x66', [1024, 66], 'div-gpt-ad- ********-0').addService(googletag.pubads());
googletag.pubads().enableSyncRendering();
googletag.pubads().enableSingleRequest();
googletag.enableServices();
</script>
DOCUMENT BODY
<div id='div-gpt-ad-**********' style='width:1024px; height:66px;'>
<script type='text/javascript'>
googletag.display('div-gpt-ad-*********');
</script>
</div>)
But, it does not display on Mobile (android project). That's why I would like to use the DFP plugin (PostMedia), but I do not know how to use that? as the plugin itself would not be good enough.
for instance, I have already had the code(above) to put in my app, but I wanna know how can i integrate that plugin with my code.
Note: In the plugin we have:
createBannerAd: function (options, successCallback, failureCallback) {
var defaults = {
'adUnitId': 1404187116182-0,
'adSize': (250, 150),
'tags': undefined,
'networkId': 4271715,
'backgroundColor': "#fff"
};
what if we want to have bunch of ads and of course we have bunch of codes generated by Google and FDP? we need to create a service ? or what?
I really appreciate any response a head,
I am using Cordova 2.8.1 / AngularJS

Here is how we use it
var successCreateBannerView = function() {
//console.log("addBanner Success");
DFPPlugin.requestAd({
'isTesting': false
}, success, error);
};
var success = function() {
//console.log("requestAd Success");
};
var error = function(message) {
//console.log("requestAd Failed " + message);
};
var options = {
'adUnitId': '/xxx/xxxx', // Replace the /xxx/xxxx with your adslot
'adSize': 'BANNER',
'tags': {},
'backgroundColor': '#FFFFFF'
};
DFPPlugin.createBannerAd(options, successCreateBannerView, error);

Related

How to add a lazy load to the script?

There is a script:
<script>
$(function (){
$('#jstree')
.jstree({
"plugins": [ "dnd", "sort", "json_data" ],
'core':{
"check_callback" : true,
"plugins" : ["contextmenu", "dnd"],
'data': {
'url': function (node) {
return node.id === '#' ? 'ajax?id=root' : 'ajax?id=' + node.id;
},
'data': function (node) {
return { 'id': node.id };
}
}
}
});
});
</script>
I need to add a delay (2 sec) on opening nodes. I readed jQuery documentation but i didn't find an answer there. Please help me how add a delay?
Answer referenced from combined two other SO answers.
Essentially, set a timeout function when the DOM loads and create a <script> tag at run time. Then just append it to the <body> and it will load.
console.log("Seconds: " + new Date().getSeconds());
setTimeout(function() {
var blob = new Blob(["console.log('Loaded after')"]); // Insert JS code into []
var script = document.createElement('script');
var url = URL.createObjectURL(blob);
script.onload = script.onerror = function() {
URL.revokeObjectURL(url);
};
script.src = url;
document.body.appendChild(script);
console.log("Seconds: " + new Date().getSeconds());
}, 2000);
<html>
<head>
</head>
<body>
<p>foo</p>
</body>
</html>

Google Sign In gapi undefined

I am trying to enable sign in with google on my site. The button works, syncs with my account, but I can not access the userId from google. This is what's in my head.
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
And this is where I'm trying to obtain the user Id. In the console I get the error message Uncaught ReferenceError: gapi is not defined. I thought I was calling gapi in the source above. Any help or suggestions would be much appreciated.
$('document').ready(function(){
var request = gapi.client.plus.people.get({
'userId' : 'me'
});
request.execute(function(resp) {
console.log('ID: ' + resp.id);
console.log('Display Name: ' + resp.displayName);
console.log('Image URL: ' + resp.image.url);
console.log('Profile URL: ' + resp.url);
});
});
Your code is calling gapi.client.plus.people.get method before loading the google api library https://plus.google.com/js/client:plusone.js. Hence you are getting gapi is not defined error.
Approach to work-
Why its not working?
We are calling https://plus.google.com/js/client:plusone.js asynchronously(non blocking) to improve the performance. With Async javascript file loading, you are not able to call the gapi method on body load.
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
</script>
To make the api call you first have to know javascript file is successfully loaded.
For this you have to call method using callback.
https://apis.google.com/js/client:plusone.js?onload=makeAPICall
Write an api request & execution it in the callback method to get data.
Check below example for this-
<html>
<head></head>
<body>
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="YOUR CLIENT ID.apps.googleusercontent.com"
data-cookiepolicy="single_host_origin"
data-scope="https://www.googleapis.com/auth/plus.login">
</span>
</span>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js?onload=signinCallback';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
document.getElementById('signinButton').setAttribute('style', 'display: none');
makeAPICall();
} else {
console.log('Sign-in state: ' + authResult['error']);
}
}
function makeAPICall(){
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function (resp){
console.log(resp);
if(resp.id){
console.log('ID: ' + resp.id);
}
if(resp.displayName){
console.log('Display Name: ' + resp.displayName);
}
if(resp.image && resp.image.url){
console.log('Image URL: ' + resp.image.url);
}
if(resp.url){
console.log('Profile URL: ' + resp.url);
}
});
});
}
</script>
</body>
</html>
Conclusion: Calling javascript API before loading the asynchronously client library.
To avoid "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.". Call makeAPICall() method only when user is logged in not on every request.

Uncaught TypeError: Cannot read property 'get' of undefined

Why am I getting this error, when I'm trying to get a response from a file on my own server?
$.get("http://www.example.com/user.php?q=" + client + "", function(response) {
if(response == "invalid"){
console.log("invalid login");
return;
}
And btw, the string client is mentioned already in the code.
And jquery is included.
http://i.gyazo.com/693e6633d211ab6da79598e75c6dde58.png
I have solve the problem like this ( i have jquery loaded async so i check if is defined and then get a css...etc..)
<script id="jquery" type='text/javascript' async defer src='//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js?ver=1.8.3'></script>
<script type='text/javascript'>
(function checkJQuery(){
if ('undefined' == typeof window.jQuery) {
setTimeout(function(){checkJQuery();},250);
}else{
var css = "url-of-my-css";
console.log("my css is loading");
window.jQuery.get( css, function( data ) {
$('<style>'+ data +'</style>').appendTo(document.getElementsByTagName('head')[0]);
console.log("css loaded");
});
var js = document.createElement('script');
js.type = 'text/javascript';
js.async = 'async';
js.defer = 'defer';
js.src = 'url-of-my-js';
var node = document.getElementsByTagName('script')[1];
node.parentNode.insertBefore(js, node);
}
})();
</script>
Changing $.get to window.JQuery.get
Hope this help.
I had a problem like this in asp.net mvc 5.
<script>
function OpenBulkUpload() {
$.get("/AdminPanel/BulkUpload/Index").then(
function (r) {
$("<div id='DivBulkUpload'></div>").html(r).dialog(
{
width: 'auto', height: 'auto', modal: true, title: "Upload Pictures",
close: function () { $('#DivBulkUpload').remove(); }});
});
}
</script>
show Uncaught TypeError: Cannot read property 'get' of undefined in debuger browser.
solution:
1.By adding jquery UI in package manager console
PM> install-package Jquery.UI.combined
2.And add scripts and links in top of cshtml page
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.js"></script>
<link href="~/Content/themes/base/all.css" rel="stylesheet" />
My problem was solved.
I think this will work:
$.get("http://www.example.com/user.php?q=" + client, function(response) {
if(response == "invalid"){
console.log("invalid login");
return;
}
});

canvg is undefined error

I am trying to use the code from Battlehorse to convert A Google Visualization chart to an image to save to a server. I was able to get this to work on localhost but when I attempt to use it on the Web Server I get the error "canvg is undefined". The Web Server is running IIS 7. I have searched quite a bit and have not been able to find any information regarding this error. Does anyone know what causes this error or how to resolve it?
http://www.battlehorse.net/page/topics/charts/save_google_charts_as_image.html
Code Sample:
<html>
<head>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<script type="text/javascript">
function getImgData(chartContainer) {
var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
var svg = chartArea.innerHTML;
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('width', chartArea.offsetWidth);
canvas.setAttribute('height', chartArea.offsetHeight);
canvas.setAttribute(
'style',
'position: absolute; ' +
'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;}
function alert10() {
try {
var textbox1 = document.getElementById('textbox1');
textbox1.value = getImgData(document.getElementById('chart1_div'));
}
catch (err) {
alert(err.message);
}
}
</script>
</head>
I figured it out. The problem was that the site was running with SSL enabled and I was calling external script files by http protocols. I had to adjust the external script file references to either use https OR change them to relative like this:
<script type="text/javascript" src="//canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="//canvg.googlecode.com/svn/trunk/canvg.js"></script>
Using the protocol relative path like "//..." makes sure it will work in both HTTP and HTTPS

FusionTables private table with OAUTH2

Good pic by Tim Rosenberg that shows exactly how OAUTH2 work's:
I'm kind a lazy to even start looking on this 2 files and test
so I searched for easyest way to
1.get token
2.access with that token
with help of gwt-oauth2
put it into index.php head :
<script type="text/javascript" src="gwt-oauth2.js"></script>
and this in body
<script type="text/javascript">
(function() {
var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
var GOOGLE_CLIENT_ID = "CLIENT_ID";
//var PLUS_ME_SCOPE = "https://www.googleapis.com/auth/plus.me";
//var FusionTable_SCOPE = "https://www.googleapis.com/auth/fusiontables";
var button = document.createElement("button");
button.innerText = "Authenticate with Google";
button.onclick = function() {
var req = {
'authUrl' : GOOGLE_AUTH_URL,
'clientId' : GOOGLE_CLIENT_ID,
'scopes': ['https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/fusiontables'
],
};
oauth2.login(req, function(token) {
alert('Got an OAuth token:\n'+ token +'\n'+ 'Token expires in '+ oauth2.expiresIn(req) +' ms\n');
}, function(error) {
alert("Error:\n" + error);
});
};
var dv = document.getElementById('admin-content');
dv.appendChild(button);
var clearTokens = document.createElement('button');
clearTokens.innerText = 'Clear all tokens'
clearTokens.onclick = oauth2.clearAllTokens;
dv.appendChild(clearTokens);
})();
</script>
OK,
Now you can see connection and redirection to oauthWindow.html in new window without errors. GET parameters now showing you access_token token_type expires_in. Check the access_token HERE
As you see access_token working great BUT
What you still don't get is first alert from that :
oauth2.login(req, function(token) {
alert('Got an OAuth token:\n' + token + '\n'
+ 'Token expires in ' + oauth2.expiresIn(req) + ' ms\n');
}, function(error) {
alert("Error:\n" + error);
});
Second alert works fine and when you try to Auth. again if oauthWindow.html still open it shows you an error alert(so it's working!)
Now let's add that little code to oauthWindow.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (window.opener && window.opener.oauth2 && window.opener.oauth2.__doLogin) {
window.opener.oauth2.__doLogin(location.hash);
} else {
document.body.innerText = "Your browser seems to be stopping this window from communicating with the main window.";
}
</script>
</head>
<body></body>
</html>
Perfect!
Now if you want to work with private tables all you need is to add an access_token to url.
Thanks for giving me the reason to answer myself!
Put this into oauthWindow.html file
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (window.opener && window.opener.oauth2 && window.opener.oauth2.__doLogin) {
window.opener.oauth2.__doLogin(location.hash);
} else {
document.body.innerText = "Your browser seems to be stopping this window from communicating with the main window.";
}
</script>
</head>
<body></body>
</html>

Categories