How to use an API based on the OAuth2.0 protocole - javascript

I'm a newbie in API requests and javascript...
I try to use an API based on the OAuth2.0 protocole (Autorisation Code Grant).
I don't understand how i can pass the first step :
why my request don't generate the redirection to the redirect_uri ?
after, how to catch the url params contain in this redirection url ?
Here, my actual code :
const link = 'https://gw.hml.api.fr/group/espace-particuliers/consentement/oauth2/authorize?client_id=MY_API_CLIENT_ID&state=fz80ac780&duration=P6M&response_type=code&redirect_uri=https://gw.hml.api.fr/redirect';
const connect = document.getElementById('connect-btn')
if (connect) {
connect.addEventListener('click', function(event) {
event.preventDefault();
fetch(link)
.then(response => response.text())
console.log(response);
// HOW TO CATCH THE REDIRECTION_URI PARAMS ?
});
};
Exemple of response :
<html lang="fr">
<head>
<meta charset="utf-8" />
</head>
<body>
<p>Veuillez patienter...</p>
<script type="text/javascript">
/**
* Delete cookies (iPlanetDirectoryPro, amlbcookie)
*/
function removeCookie(cookieName) {
cookieValue = "";
cookieLifetime = -1;
var date = new Date();
date.setTime(date.getTime() + (cookieLifetime*24*60*60*1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = cookieName+"=" + JSON.stringify(cookieValue) + expires+"; path=/; domain=.ene.fr";
}
removeCookie("iPlanetDirectoryPro");
removeCookie("amlbcookie");
/**
* Parse url query
*/
var parseQueryString = function( queryString ) {
var params = {}, queries, temp, i, l;
// Split into key/value pairs
queries = queryString.split("&");
// Convert the array of strings into an object
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
}
return params;
};
var url = "https://gw.hml.api.fr/redirect?code=sD4F5RT3qPPJ15qFhrGu32YiumzN5D&state=fz80ac780&usage_point_id=225158214714453";
// Get redirect_uri params
var queryString = url.substring( url.indexOf('?') + 1 );
var params = parseQueryString(queryString);
var forceNonAutomaticClose = params.close !== undefined && params.close == 'false';
// Avoid closing popup
if (forceNonAutomaticClose || !this.window.opener || this.window.opener.closed) {
this.window.location.href = url;
} else if (this.window.opener && !this.window.opener.closed) {
// Close popup
this.window.opener.location.href = url;
this.window.close();
}
</script>
</body>
</html>
How I can complete my code ?
Thanks !

Related

How do I fix 401 error when using OMDB API?

EDIT: I have added the response from OMDB
{Response: "False", Error: "Invalid API key!"}
Error: "Invalid API key!"
Response: "False"
I am new to web development and I am trying to build a chrome extension that displays imdb scores on netflix. I am using the OMDB API to do this. At first I got the following error:
"Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint ''. This request has been blocked; the content must be served over HTTPS.",
however I just changed the "http" in the url to "https" and it went away. However, now I am getting a 401 error, which I think means my access is being denied.
This is a picture of the full error
Here is the code for the extension
Manifest file:
{
"manifest_version": 2,
"name": "1_ratings_netflix",
"version": "0.1",
"description": "Display imdb ratings on netflix",
"content_scripts": [
{
"matches": [
"https://www.netflix.com/*", "https://www.omdbapi.com/*"
],
"js": ["content.js"]
}
],
"icons": { "16": "icon16.png", "48":"icon48.png"},
"permissions": [
"https://www.netflix.com/*", "https://www.omdbapi.com/*"
]
}
Content File:
function fetchMovieNameYear() {
var synopsis = document.querySelectorAll('.jawBone .jawbone-title-link');
if (synopsis === null) {
return;
}
var logoElement = document.querySelectorAll('.jawBone .jawbone-title-link .title');
if (logoElement.length === 0)
return;
logoElement = logoElement[logoElement.length - 1];
var title = logoElement.textContent;
if (title === "")
title = logoElement.querySelector(".logo").getAttribute("alt");
var titleElement = document.querySelectorAll('.jawBone .jawbone-title-link .title .text').textContent;
var yearElement = document.querySelectorAll('.jawBone .jawbone-overview-info .meta .year');
if (yearElement.length === 0)
return;
var year = yearElement[yearElement.length - 1].textContent;
var divId = getDivId(title, year);
var divEl = document.getElementById(divId);
if (divEl && (divEl.offsetWidth || divEl.offsetHeight || divEl.getClientRects().length)) {
return;
}
var existingImdbRating = window.sessionStorage.getItem(title + ":" + year);
if ((existingImdbRating !== "undefined") && (existingImdbRating !== null)) {
addIMDBRating(existingImdbRating, title, year);
} else {
makeRequestAndAddRating(title, year)
}
};
function addIMDBRating(imdbMetaData, name, year) {
var divId = getDivId(name, year);
var divEl = document.getElementById(divId);
if (divEl && (divEl.offsetWidth || divEl.offsetHeight || divEl.getClientRects().length)) {
return;
}
var synopsises = document.querySelectorAll('.jawBone .synopsis');
if (synopsises.length) {
var synopsis = synopsises[synopsises.length - 1];
var div = document.createElement('div');
var imdbRatingPresent = imdbMetaData && (imdbMetaData !== 'undefined') && (imdbMetaData !== "N/A");
var imdbVoteCount = null;
var imdbRating = null;
var imdbId = null;
if (imdbRatingPresent) {
var imdbMetaDataArr = imdbMetaData.split(":");
imdbRating = imdbMetaDataArr[0];
imdbVoteCount = imdbMetaDataArr[1];
imdbId = imdbMetaDataArr[2];
}
var imdbHtml = 'IMDb rating : ' + (imdbRatingPresent ? imdbRating : "N/A") + (imdbVoteCount ? ", Vote Count : " + imdbVoteCount : "");
if (imdbId !== null) {
imdbHtml = "<a target='_blank' href='https://www.imdb.com/title/" + imdbId + "'>" + imdbHtml + "</a>";
}
div.innerHTML = imdbHtml;
div.className = 'imdbRating';
div.id = divId;
synopsis.parentNode.insertBefore(div, synopsis);
}
}
function getDivId(name, year) {
name = name.replace(/[^a-z0-9\s]/gi, '');
name = name.replace(/ /g, '');
return "aaa" + name + "_" + year;
}
function makeRequestAndAddRating(name, year) {
var url = "https://www.omdbapi.com/?i=tt3896198&apikey=**{API_KEY}**" + encodeURI(name)
+ "&y=" + year + "tomatoes=true";
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (xhr.status === 200) {
var apiResponse = JSON.parse(xhr.responseText);
var imdbRating = apiResponse["imdbRating"];
var imdbVoteCount = apiResponse["imdbVotes"];
var imdbId = apiResponse["imdbID"];
var imdbMetaData = imdbRating + ":" + imdbVoteCount + ":" + imdbId;
window.sessionStorage.setItem(name + ":" + year, imdbMetaData);
window.sessionStorage.setItem("metaScore:" + name + ":" + year, metaScore)
window.sessionStorage.setItem("rotten:" + name + ":" + year, rottenRating);
addIMDBRating(imdbMetaData, name, year);
addRottenRating(rottenRating, name, year);
addMetaScore(metaScore, name, year);
}
};
xhr.send();
}
if (window.sessionStorage !== "undefined") {
var target = document.body;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
window.setTimeout(fetchMovieNameYear, 5);
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(target, config);
}
It would be helpful for you to post the request and response for OMDB (you can find them in the "Network" tab in dev tools).
One thing that triggers CORS (cross-origin requests) errors is specifying a content type other than application/x-www-form-urlencoded, multipart/form-data or text/plain. If I recall correctly, the OMDB API will return a JSON response even without specifying the content type of the request, so you should try removing the line:
xhr.setRequestHeader('Content-Type', 'application/json');
More on "Simple Requests" which do not trigger CORS: https://javascript.info/fetch-crossorigin#simple-requests
You also need to get an API key (https://www.omdbapi.com/apikey.aspx) and replace
**{API_KEY}** in your code with the key. You also need to add the t key to your querystring or the title will be appended to your API key.
var url = "https://www.omdbapi.com/?i=tt3896198&apikey=**{API_KEY}**" + "&t="
+ encodeURI(name) + "&y=" + year + "tomatoes=true";

How to send data from javascript function to Django View

I am trying to send data from a javascript function that generates a random string upon the page loading to a Django view. I don't know how to structure the script tag to send the data after the page has loaded and the views.py to receive the data. I am new to javascript and don't quite know how to go about this. I appreciate any help provided.
index.html
<script>
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(makeid(9));
</script>
You can use ajax to send data to Django view like following code.
javascript:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
$.ajax({
type: "GET",
url: '/my_def_in_view',
data: {
"result": result,
},
dataType: "json",
success: function (data) {
// any process in data
alert("successfull")
},
failure: function () {
alert("failure");
}
});
}
urls.py:
urlpatterns = [
url(r'^my_def_in_view$', views.my_def_in_view, name='my_def_in_view'),
...
]
views.py:
def my_def_in_view(request):
result = request.GET.get('result', None)
# Any process that you want
data = {
# Data that you want to send to javascript function
}
return JsonResponse(data)
If it was successfull it goes back to "success" part.
you can do that in two ways:
Tradicional with ajax
Websockets: With django channels
If you want to send a bit of information, an ajax request is enough, you have to set and address and a view to receive the POST or GET ajax request.
I recommend to you use pure JS, not jquery
For example, this is a call to refresh a captcha image....
/*Agregar boton refresh al lado del campo input*/
let captcha_field =
document.getElementById('captcha-field-registro_1').parentNode;
let refresh_button=document.createElement('BUTTON');
refresh_button.addEventListener('click',refresh_captcha)
refresh_button.innerHTML = "Refrescar Captcha"; // Insert text
captcha_field.appendChild(refresh_button);
let url_captcha= location.protocol + "//" +
window.location.hostname + ":" +
location.port + "/captcha/refresh/";
let id_captcha_0="captcha-field-registro_0"
function refresh_captcha(){
let xhr = new XMLHttpRequest();
xhr.open('GET', url_captcha, true);
xhr.onload = function recv_captcha_load(event){
console.log("event received", event,
"state",xhr.readyState);
let data_txt = xhr.responseText;
let data_json = JSON.parse(data_txt);
console.log("Data json", data_json);
if (xhr.readyState==4){
if (xhr.status==200){
console.log("LOAD Se ha recibido esta informaciĆ³n", event);
let captcha_img=document.getElementsByClassName('captcha')[0];
console.log("Catpcha img dom", captcha_img);
captcha_img.setAttribute('src', data_json['image_url'])
document.getElementById(id_captcha_0).value=data_json['key']
}
else{
console.log("Error al recibir")
}
}
};
var csrftoken = getCookie('csrftoken');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.send();
}
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}

How to call in tag manager data after user OAUTH2 authorization is complete (JavaScript)?

I've been at this all day trying to figure out how to do an XMLHTTP request after authorization but just can't for the life of me figure it out.
So far I've got the code below which authorizes the user.
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?
access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile
https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = 'NOT SHOWING FOR SECURITY REASONS';
var REDIRECT = 'NOT SHOWING FOR SECURITY REASONS'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
The code works fine as far as the login goes. It's after logging in that I don't know what to do. I've tried multiple ideas and have gotten nowhere. Any ideas on how I can call tags from tag manager in "readonly" mode after this login?
Hi I just decided to try using the JavaScript web app method and was able to get this working. If you run into the same issue using the ajax version here is the documentation! Make sure to select the JavaScript tab or you can try the oAuth2.
https://developers.google.com/identity/protocols/OAuth2UserAgent

Cookie is only being stored on specific pages

I wrote a script in JS that will retrieve the traffic source of the user and store that value in a cookie.
For all but three pages this works. If the user's landing page is for example www.example.com/example1, www.example.com/example2 or www.example.com/example3 the cookie gets stored on those pages only. I do not see see it in developer tools on chrome but when I write document.cookie I do see the cookie I created. I also see it in settings.
But if I were to navigate to another page it doesn't get stored.
It works fine on all other pages, the user enters on the landing page and the cookie stays stored during the whole session. Except on the above pages.
The hostname is the same for all pages.
Any ideas?
var source = trafficSource();
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
var source = document.referrer;
}
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
function checkCookie() {
var verifyCookie = getCookie("Traffic Source Cookie");
if (verifyCookie != null ){
//alert("there is a cookie");
return "";
}else{
setCookie("Traffic Source Cookie", source, 30);
//alert("new cookie made");
}
}
checkCookie();
var trafficSourceValue = getCookie("Traffic Source Cookie"); // delete if doesnt work
//dataLayer.push( "Cookie Traffic Source is " +getCookie("Traffic Source Cookie"));
function trafficSource(trafficType){
var trafficType;
//set traffic sources to variables
/*var sourceSearchEngine = searchEngine();
var sourceSocialNetwork = socialNetwork();
var sourcePaidSearch = paidSearch(); */
// get what kind of referrer
var trafficReferrer = document.referrer;
var trafficURL = document.URL;
if(trafficURL.indexOf("gclid") > -1) {
trafficType = paidSearch();
//alert("paidSearch google");
} else if (trafficURL.indexOf("bing") >-1 &&(trafficURL.indexOf("ppc")> -1) || (trafficURL.indexOf("cpc") >-1)){
trafficType = paidSearch();
//alert("paidSearch bing");
}
else if((trafficReferrer.indexOf("plus.url.google.com")<= 0) && trafficReferrer.indexOf("google")>-1 || trafficReferrer.indexOf("bing")>-1 || trafficReferrer.indexOf("baidu") >-1 || trafficReferrer.indexOf("yahoo") > -1 && (trafficURL.indexOf("ppc") < 0)){
trafficType = searchEngine();
//alert("searchEngine");
//(trafficReferrer.indexOf("facebook","googleplus", "twitter", "t.co/", "linkedin", "pinterest","reddit","disqus","blogspot.co.uk") >-1
} else if ((trafficReferrer.indexOf("facebook")>-1) || (trafficReferrer.indexOf("plus.url.google.com")>-1) || (trafficReferrer.indexOf("t.co/")>-1) || (trafficReferrer.indexOf("linkedin")>-1) || (trafficReferrer.indexOf("reddit")>-1) || (trafficReferrer.indexOf("disqus")>-1) || (trafficReferrer.indexOf("blogspot.co.uk")>-1) || (trafficReferrer.indexOf("t.umblr")>-1)) {
trafficType = socialNetwork();
//alert("socialNetwork");
} else if (trafficReferrer.indexOf("")>-0){
trafficType = directSource();
//alert("direct");
}else if (trafficURL.indexOf("display") >-1 || trafficURL.indexOf("Display") >-1){
trafficType = display();
//alert("display");
}else if (trafficReferrer === "" || trafficReferrer === null){
trafficType = "Direct";
}else {
//var hostnameReturn = hostname.split("www.");
var returnReferrer = document.referrer.match(/https?:\/\/([^\/]*)(?:\/|$)/i)[1].replace(/www\./, "");
// do I need this snippet
trafficType = returnReferrer + "/Referral" ;
//alert("Hostname Referral");
}
//Return the trafficType which is the function that will get source
return trafficType;
// alert("trafficType");
}
//setCookie("trafficSource",1,30)
//search engine source
function searchEngine (referrer){
var search = document.referrer;
var bing = "bing";
var google ="google";
var yahoo = "yahoo";
var ask = "ask";
var msn = "msn";
var baidu = "baidu";
var referrer;
if (search.indexOf(bing)> -1){
//alert(bing);
referrer = bing + " organic";
} else if (search.indexOf(yahoo)>-1){
// alert(bing);
referrer = yahoo + " organic";
} else if (search.indexOf(ask)>-1){
referrer = ask + " organic";
} else if (search.indexOf(msn)>-1){
// alert(bing);
referrer = msn + " organic";
} else if (search.indexOf(baidu)>-1){
// alert(baidu);
referrer = baidu + " organic";
}
else{
// alert(google);
referrer = google + " organic";
}
return referrer;
// alert("Search Engine: " + referrer);
}
//search social network
function socialNetwork (referrer){
var search = document.referrer;
var facebook ="facebook";
var twitter = "twitter";
var googlePlus = "google plus";
var googlePlus2 = "plus.url.google.com";
var pinterest ="pinterest";
var linkedin = "linkedin";
var tumblr = "t.umblr";
var reddit = "reddit";
//var beforeItsNews ="news";
var disquis = "disqus";
var blogger = "blogspot.co.uk";
//var StumbleUpon = "StumbleUpon";
var referrer;
if(search.indexOf(facebook)> -1){
// alert(facebook);
referrer = "Social/ " + facebook;
}else if (search.indexOf(twitter)> -1 || search.indexOf("t.co/") >-1){
// alert(twitter);
referrer = "Social/ "+ twitter;
}else if (search.indexOf(pinterest)> -1){
//alert(pinterest);
referrer = "Social/ "+ pinterest;
}else if (search.indexOf(linkedin) >- 1){
//alert(linkedin);
referrer = linkedin;
}else if (search.indexOf(googlePlus) >-1 || search.indexOf(googlePlus2) >-1){
// alert(googlePlus);
referrer = "Social/ "+ googlePlus;
}else if (search.indexOf(tumblr) >-1){
// alert(googlePlus);
referrer ="Social/ "+ "tumblr";
}else if (search.indexOf(reddit) >-1){
// alert(googlePlus);
referrer = "Social/ " + reddit;
}else if (search.indexOf(disquis) >-1){
//alert(disquis);
referrer = "Social/ "+ disquis;
}else if (search.indexOf(blogger) >-1){
blogger ="Blogger";
//alert(blogger);
referrer = "Social/ "+ blogger;
}else{
// alert(document.referrer);
referrer = "Referral: " + document.referrer;
// alert("Check Cookie - Referrer");
}
return referrer;
// alert("Social Media Network: " + referrer)
}
// search for paid search
function paidSearch(referrer){
var paidCampaign = document.URL;
var campaignReferrer = document.referrer;
var referrer;
var googleAd = "gclid";
var justGoogle = "google";
var justBing = "ppc";
var bingAd = "Bing";
if (paidCampaign.indexOf(googleAd) >- 1 || campaignReferrer.indexOf(justGoogle) >-1){
googleAd = "Google/CPC ";
// alert(googleAd);
//referrer = paidCampaign; < original code but trying the code on the bottom>
referrer = googleAd;
// alert(referrer);
}
if (paidCampaign.indexOf(bingAd)>- 1 || paidCampaign.indexOf(justBing) >-1){
bingAd = "Bing/CPC ";
//alert(bingAd);
referrer = bingAd ;
}
return referrer;
// alert("The paid ad is: " + googleAd);
}
function directSource(referrer){
var directVistor = document.referrer;
if(directVistor ==="" || directVistor === null ){
referrer = "Direct";
//alert("Direct");
}
return referrer;
}
function display(referrer){
var displayURL = document.URL;
var referrer;
if(displayURL.indexOf("display") >- 1 || displayURL.indexOf("Display")>-1){
var returnDisplay = window.location.search.substring(1);
referrer = "Display: " + returnDisplay;
//alert(referrer);
return referrer;
}
}
// function urlSpilt(url){
// // return utm_source and utm_medium if iti has it.
// var url;
// var getURL = document.URL;
// //var testURL = "http://www.franciscoignacioquintana.com/?utm_source=testSource&utm_medium=testMedium&utm_campaign=testName";
// var getURL = getURL.split("utm_source");
// getURL = getURL[1].split("utm_source");
// url = getURL;
// return url;
// }
//http://www.currencies.co.uk/?utm_source=testSource&utm_medium=testMedium&utm_campaign=testName
function getQueryParam(par){
//var strURL = document.URL;#
var strURL = document.referrer;
var regParam = new RegExp("(?:\\?|&)" + par + "=([^&$]*)", "i");
var resExp = strURL.match(regParam);
if((typeof resExp == "object") && resExp && (resExp.length > 1)){
return resExp[1];
}
else{
return "";
}
}
//var hostname = window.location.hostname;
//var hostnameReturn = hostname.split("www.");
//var hostname2 = hostname.slice(4);

Disqus in Ionic APP

I am trying to implement disqus commments in my ionic app. I know I have to host it on the domain its setup for which I believe I have configured correctly. Any assistance will be welcomed
Here is the code in my app.js for the ionic app
$scope.showComments = function () {
$scope.currentView = "comments";
//loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
//
var disqus_title = "Venue 1";
var disqus_identifier = '/venue/' + $stateParams.id;
var disqus_url = 'liverpool.li/venue/' + $stateParams.id;
var url = "http://liverpool.li/app/disqus.html?";
$scope.url = url + "shortname=liverpoolli&url=" + encodeURIComponent(disqus_url) +
"&title=" + encodeURIComponent(disqus_title) + "&identifier=" + encodeURIComponent(disqus_identifier);
$scope.url = $sce.trustAsResourceUrl($scope.url);
};
$scope.$on("$destroy", function () {
if ($scope.lastScriptElm && $scope.lastScriptElm.parentNode) {
$scope.lastScriptElm.parentNode.removeChild($scope.lastScriptElm);
$scope.lastScriptElm = null;
}
});
And the page it points to (disqus.html) located on my domain
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
<div id="disqus_thread"></div>
<script type="text/javascript">
var params;
var disqus_url;
var disqus_title;
var disqus_shortname;
var disqus_identifier;
window.onload = function () {
var match,
pattern = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pattern, " ")); },
query = window.location.search.substring(1);
params = {};
while (match = search.exec(query))
params[decode(match[1])] = decode(match[2]);
if (params["shortname"] === undefined || params["url"] === undefined || params["title"] === undefined) {
alert("Required arguments missing");
}
else {
loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
}
};
function loadComments(shortname, url, title, identifier) {
disqus_url = url;
disqus_title = title;
disqus_shortname = shortname;
if (identifier !== undefined)
disqus_identifier = identifier;
else
disqus_identifier = "";
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = false;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
blog comments powered by <span class="logo-disqus">Disqus</span>
</body>
</html>
I get the following error
we were unable to load disqus. if you are a moderator please see our
troubleshooting guide.
It looks like you're almost there. The only issue I see is the disqus_url variable must also include the protocol to be valid. Try using this line instead:
var disqus_url = 'http://liverpool.li/venue/' + $stateParams.id;

Categories