I developing a web application where each user can create the his own pages using the widgets provided and disqus api is one of the widgets. I trying to use the disqus api http://docs.disqus.com/developers/universal/ for the web site, but I am little confused or I can say not able to do few things,let me explain u with a scenario. Suppose user A comes and adds disqus widget in his page and he can access his page through this url say "www.domain.com/xxx" where he can use his disqus widget, I am using the universal api but I guess I need to dynamically update the disqus_identifier and also disqus_url. How do I do it dynamically for different users or multiple users.
Kindly help me out
The disqus_identifier and disqus_url parameters are not required for Disqus to embed. However, depending on the functionality you are looking for (which is not clear from your question) you may need them to satisfy your requirements.
Since your page is composed of widgets, I assume there is no "permalink" URL that links to just the Disqus widget. For that reason, I would recommend you do not set the disqus_url parameter at all. (By not setting this parameter, disqus will figure out the appropriate URL on its own.)
The method you use to set the disqus_identifier will determine how and when a new disqus thread appears in the widget. If you want each user to see a unique disqus thread in their widget, set disqus_identifier to that user's ID. In JSP, this might look something like the following (but the actual implementation completely depends on your unique application).
// ...
%>
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'example'; // required: replace example with your forum shortname
// The following are highly recommended additional parameters. Remove the slashes in front to use.
var disqus_identifier = '<%=currentUser.getID()%>';
// var disqus_url = 'http://example.com/permalink-to-page.html';
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<%
Related
I owned a google form, how can I get the js script of it?
I click the Script Editor but there is no corresponding js I can find.
I have already searched on internet but no expected answers.
--
update on 20/08/2017
Assume that I owned a form like this :
Sample Form.
How can I get the corresponding google script of this form?
i.e.,
function myFunction() {
// Create a new form, then add a checkbox question, a multiple choice question,
// a page break, then a date question and a grid of questions.
var form = FormApp.create('Sample Form');
var sect1 = form.addSectionHeaderItem();
var item = form.addCheckboxItem();
item.setTitle('What condiments would you like on your hot dog?');
item.setChoices([item.createChoice('Ketchup'), item.createChoice('Mustard'), item.createChoice('Relish')]);
var item2 = form.addMultipleChoiceItem().setTitle('Do you prefer cats or dogs?');
// .setChoiceValues(['Cats','Dogs'])
// .showOtherOption(true);
var sect2 = form.addSectionHeaderItem();
form.addPageBreakItem().setTitle('Getting to know you');
form.addDateItem().setTitle('When were you born?');
var sect3 = form.addSectionHeaderItem();
var break2 = form.addPageBreakItem().setTitle('Getting to know you 2');
var choice1 = item2.createChoice('cat', FormApp.PageNavigationType.CONTINUE);
var choice2 = item2.createChoice('dog', break2);
item2.setChoices([choice1, choice2]);
form.addGridItem().setTitle('Rate your interests').setRows(['Cars', 'Computers', 'Celebrities']).setColumns(['Boring', 'So-so', 'Interesting']);
Logger.log('Published URL: ' + form.getPublishedUrl());
Logger.log('Editor URL: ' + form.getEditUrl());
}
Google Script Editor is a way that Google allows people to make their forms (and many other Google services) more flexible and customizable. You can even create Add-ons using Google Scripts. But there is not such thing as a default user script for each form; all forms begin with no user Google Scripts at all and it is up to you to add some more functionality by writing some new scripts.
Now, if you mean to get the javascript source of that form, then you can use Developer Tools in Chrome (F12 key in Windows) and go to sources, there you'll see all the cripts that Google uses for the forms:
And if you left click the form and view the source of it, you'll see some more small script blocks mostly related to the data that the Google Form has:
<script>_docs_flag_initialData={ ....
<script>;this.gbar_={CONFIG:[[[0,"www.gstatic.com", ....
<script type="text/javascript">var FB_PUBLIC_LOAD_DATA_ = [null,[null, ....
Another approach can be to create a html form yourself and send a request to a Google Apps Script Web app. See this example if you want to try it out: https://gist.github.com/mhawksey/1276293
Regards, Peter
I've been using Google Web Designer for a few months and I have a question. I don't know if it's possible to do in GWD:
I want the index.html file to load a different random page, choosing between 3 pages. When you hit reload, it should load another random page, and so on. The pages don't need to appear in order. I'm trying to find out how this can be done but I had no success so far.
This can be accomplished with a custom JavaScript event handler.
The <gwd-doubleclick> element fires an adinitialized event before any content is displayed, which we can use to make sure our changes are applied before the user sees the first page. It also provides a .goToPage(n) method which we can use to switch pages. (goToPage has additional arguments that can be used to control animation between pages, but we can ignore those because we want the default behaviour of instantly jumping.)
Start by adding a new event handler.
target: document.body
event: Google Ad: Ad Initialized
action: Custom: Add Custom Action
configuration: a name of your choice (such as gwd.goToRandomPage), for the following code:
var pages = 3; // adjust as appropriate
var targetPage = Math.floor(Math.random() * pages);
event.target.goToPage(targetPage);
In code view you can see that this produces something like the following:
// This script block is auto-generated. Please do not edit!
gwd.actions.events.registerEventHandlers = function(event) {
gwd.actions.events.addHandler('document.body', 'adinitialized', gwd.goToRandomPage, false);
};
gwd.actions.events.deregisterEventHandlers = function(event) {
gwd.actions.events.removeHandler('document.body', 'adinitialized', gwd.goToRandomPage, false);
};
You could choose to skip the GWD UI and use the standard JavaScript event handling APIs to accomplish the same thing, with something along the lines of:
document.body.addEventListener('adinitialized', function() {
var pages = 3; // adjust as appropriate
var targetPage = Math.floor(Math.random() * pages);
event.target.goToPage(targetPage);
});
However, you probably want to avoid this in general, because it will prevent GWD from handling things like element renaming automatically.
If you'd like to jump to one of a specific set of pages, instead of selecting from all pages, you could use an array of page IDs instead.
var pageIds = ['page1_1', 'page1_2'];
var targetPage = pageIds[Math.floor(Math.random() * pageIds.length)];
event.target.goToPage(targetPage);
For future reference, you can find most of the component APIs described in the documentation. Questions about GWD that do not involve code or are otherwise unsuitable for Stack Overflow should be asked on the GWD support forum instead.
We are developing a completely new mobile version of our site, it is a HTML5 site written using Sencha Touch 2 (Ext JS, JavaScript).
We are using Google Analytics on our main site, and we would like to use GA on the mobile site as well. However our desired use case is a little special:
We would like hits to articles on the mobile site to be tracked as hits to the corresponding article on the main site.
The reasoning behind this is the desire to aggregate the statistics, and not have the data tracked separately.
The domains and URL structure is different for the two sites, although the site hierarchy is somewhat similar (they both get content from a Sharepoint backend), and herein lies the challenge. We cannot only change the domain using something like 'setDomainName'.
On every page in the mobile version, we have available the full URL to the original page/article on the main site. What we would like to do is tell Google to track the view as a hit to that URL instead of the one we are actually on.
I've seen some threads (f ex here) regarding 'trackPageView' and it may be sufficient for our needs, however I am not entirely sure. It sounds a little too simple, but it may also be that I am not seeing the obvious solution here.
Could we provide this method with the desired hit URL and that's it? Would it work then to have a script in the header that checks for a set variable with this URL, and if it exists call 'trackPageView' with it as a parameter, if not just track a regular hit?
Any help with syntax for this approach is welcome.
All help & suggestions appreciated here!
I've scoured GA docs without much helping information on this special case.
Yes it is that simple use the track page view event and pass the corresponding URL parameters. In sencha all your views are going to exist in the same HTML page so you need to call this programmatically.
Include the same tracking code as you use in your live site with the same ID... This should work as you expect...
Very good question...Hope it helps...
Here's GA Tracking spelled out and made simple for ST2+. I've included how to initialise, set up basic navigation tracking, and several alternatives including custom variable & event tracking.
/*
Standard method to init GA tracking.
These can be fired from launch.
*/
initialiseGoogleAnalytics : function() {
//Add Google Analytics Key
window._gaq = window._gaq || [];
window._gaq.push(['_setAccount', MyApp.config.googleAnalytics.code]);
window._gaq.push(['_setDomainName', MyApp.config.googleAnalytics.domain]);
window._gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
},
/*
This method can be set to a globally accessable reference.
For instance:
MyApp.Util = {}; // reference for common utility functions
MyApp.Util.gaTrackEvent = function(data) {};
Thus allowing MyApp.Util.gaTrackEvent(data) from anywhere in app.
Alternatively, add as function to Application for
this.getApplication().gaTrackEvent(data);
*/
gaTrackEvent : function(data) {
//Push data to Google Analytics
// optional prefix for mobile devices - unnecessary for your interest
var prefix = 'mobile/';
// don't track homepage/default hits
if (data == 'home') {
//Ignore Home
return;
}
// basic tracking
_gaq.push(['_trackPageview', prefix + data]);
// OPTIONAL ALTERNATIVES FOR DETAILED TRACKING
// detailed tracking - condensed
_gaq.push(['_setCustomVar',
1, // custom variable slot
'customEventName', // custom variable name
'value1|value2|value3', // multiple values using 1 slot
2 // sets scope to session-level
]);
_gaq.push(['_trackEvent',
'ParentEventName',
'SomeValue'
]);
// detailed tracking - each variable using own slot
_gaq.push(['_setCustomVar',
1,
'stage1',
'value1',
2
]);
_gaq.push(['_setCustomVar',
2,
'stage2',
'value2',
2
]);
_gaq.push(['_setCustomVar',
3,
'stage3',
'value3',
2
]);
_gaq.push(['_trackEvent',
'ParentEventName',
'SomeValue'
]);
}
/*
Set up a controller to handle GA tracking.
This way you can keep the unique events you wish to track central,
while also handling default tracking and SEO.
For example, a controller for Registration might want tracking on success.
this.getRegistration().fireEvent('registrationsuccess');
*/
config: {
control: {
"navigationview": {
activeitemchange: 'generalSEOhandler'
},
"#registration": {
registrationsuccess: 'onRegistrationSuccess'
},
...
},
},
generalSEOhandler: function(container, value, oldValue, eOpts) {
if (value === 0) {
return false;
}
// ignoreDefaultSeo - boolean custom config that can be applied to views.
var ignoreDefaultSeo = value.getInitialConfig('ignoreDefaultSeo');
if (Ext.isDefined(ignoreDefaultSeo) && ignoreDefaultSeo == 1) {
// optional handler for special cases...
} else {
// Use default
var itemId = value.getItemId();
itemId = itemId.replace(/^ext-/,''); // Remove the prefix ext-
itemId = itemId.replace(/-[0-9]?$/,''); // Remove the suffix -1,-2...
// Alternatively use xtype of the view (my preference)
// This will require the xtypes of your views to match the main site pages.
var itemId = value.config.xtype;
this.trackEvent(itemId);
//console.log('USE DEFAULT', value.getId(), value.getItemId(), value);
}
},
onRegistrationSuccess: function(eventOptions) {
var app = this.getApplication(),
trackUrl;
trackUrl = 'new-member';
if (Ext.isDefined(app.accountReactivated) && app.accountReactivated == 1) {
trackUrl = 'reactivated-member';
}
if (Ext.isDefined(app.registeredUsingFacebook) && app.registeredUsingFacebook == 1) {
trackUrl += '/facebook';
} else {
trackUrl += '/non-facebook';
}
// console.log('onRegistrationSuccess', trackUrl);
this.trackEvent(trackUrl);
},
trackEvent: function(data) {
// if using MyApp.Util.gaTrackEvent() technique
MyApp.Util.gaTrackEvent(data);
// if gaTrackEvent() an application method
this.getApplication().gaTrackEvent(data);
}
}
I found this article talking about Google Analytics and Sencha Touch
http://wtcindia.wordpress.com/2013/03/21/using-google-analytics-in-sencha-touch-based-mobile-website/
Since Google image search API is deprecated, one should use Google custom search API for this.
I've made a small example using it. My problem is I want to return google image search results only. Whereby this shows web results, and the user may switch to the image result. How can I show only the image results by default?
<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'hu'});
google.setOnLoadCallback(function() {
var customSearchOptions = {
enableImageSearch: true,
imageSearchOptions: {
layout: google.search.ImageSearch.LAYOUT_CLASSIC
}
};
var options = new google.search.DrawOptions();
options.setAutoComplete(true);
var customSearchControl = new google.search.CustomSearchControl('XXX', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
customSearchControl.setAutoCompletionId('XXX');
customSearchControl.draw('cse', options);
}, true);
</script>
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />
The API documentation is quite poor, it only describes how to add additional results.
Google images search is now supported in the Custom Search Engine API. See the API parameters section of this page. I'm using the API with python and for my application I just specify the parameter in the API call.
searchType = "image"
See this post on the cse blog.
EDIT: As Marc points out in his comment below, you need to click "Enable image search" in your CSE console.
Per the Google Custom Search Element Control API - documentation web site, this is possible.
https://developers.google.com/custom-search/docs/element
This is the fragment used for searching by image by default:
'defaultToImageSearch'
So I believe the full syntax for using this would be:
<script>
.
// Google custom search code, ids go here...
.
</script>
<gcse:search></gcse:search>
**<gcse:searchresults enableImageSearch="true" defaultToImageSearch="true">**
For those going through the WebExtensions tutorial, here's the updated code I used in popup.js to make it work with the new CSE functionality:
/**
* #param {string} searchTerm - Search term for Google Image search.
* #param {function(string,number,number)} callback - Called when an image has
* been found. The callback gets the URL, width and height of the image.
* #param {function(string)} errorCallback - Called when the image is not found.
* The callback gets a string that describes the failure reason.
*/
function getImageUrl(searchTerm, callback, errorCallback) {
// Google image search - 100 searches per day.
// https://developers.google.com/image-search/
// var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images' +
// '?v=1.0&q=' + encodeURIComponent(searchTerm);
var searchUrl = 'https://www.googleapis.com/customsearch/v1' +
'?key=' + key + '&cx=' + cx + '&searchType=image&q=' + encodeURIComponent(searchTerm);
var x = new XMLHttpRequest();
x.open('GET', searchUrl);
// The Google image search API responds with JSON, so let Chrome parse it.
x.responseType = 'json';
x.onload = function() {
// Parse and process the response from Google Image Search.
var response = x.response;
if (!response || !response.items || response.items.length === 0) {
errorCallback('No response from Google Image search!');
return;
}
var firstResult = response.items[0];
// Take the thumbnail instead of the full image to get an approximately
// consistent image size.
var imageUrl = firstResult.image.thumbnailLink;
var width = parseInt(firstResult.image.thumbnailWidth);
var height = parseInt(firstResult.image.thumbnailHeight);
console.assert(
typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
'Unexpected respose from the Google Image Search API!');
callback(imageUrl, width, height);
};
x.onerror = function() {
errorCallback('Network error.');
};
x.send();
}
Mainly it's changing the search URL (which should have searchType=image as mentioned) and the response structural references in getImageUrl, and setting up the CSE engine. Make sure your CSE has Image search turned on, and under Sites to search make sure to select Search the entire web but emphasize included sites from the options list.
I'm not 100% certain on this, but I don't think the API supports what you're trying to do. This is not at all surprising, as Google's search API's are infamous for being lacking in even basic functionality (such as the standard search API's limit of 20 results, etc). I think the fact that I'm the first person to answer this in the 3 days it's been active is another indication that this is probably just not supported (or, if it is, Google never bothered to tell anyone).
I know you're not going to like this, but I think your best option is to scrape the images out of the returned result set yourself. That's typically what people have to resort to when dealing with Google results data. Fortunately, their frontend code is remarkably consistent, so a few well-tuned regex matches and/or splits should do the trick for ya.
And yes, it's total BS that Google has provided such lousy support for this API. =)
Try adding this line:
customSearchOptions['disableWebSearch'] = true;
I tried to get a more authoritative answer in the official Google AJAX APIs group,
and it seems the answer is NO(!). Google custom search API currently does not support image search only. You can use the deprecated Google image search API instead.
check this
Try this one
customSearchOptions['searchType'] = "image"
customSearchOptions['enableImageSearch'] = true
customSearchOptions['disableWebSearch'] = true;
I've been trying to find a solution for this but haven't seen anything useful google'ing around. The issue might be that i'm using terminology that has other meanings.
I have a site that has utilizes the same URL's for both guests and members. In order to track visits and goals correctly i need a way to tell if the visitor is a logged in user or a guest.
The easiest way i can think of is if i just prefix my URL's with something like
/member/
I thought maybe i could do this in the google tracking code by adding this:
_gaq.push(['_trackPageview'], '/member' + window.location.pathname);
the full code is:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'xxxxxxxxxx']);
_gaq.push(['_trackPageview'], '/member' + window.location.pathname);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
However this isn't working, also reading the google analytic docs, this seems to be a way to add an 'additional' page view.
I can update the servers code to prefix the urls with /member/ and then strip it before processing the path for the controllers, but i would rather not risk breaking a stable system thats about to go live.
Does anyone know how this can be done in JS before the normal URL is tracked?
Thanks,
Dan
You have a minor syntax error with your _trackPageview call.
It should just be this:
_gaq.push(['_trackPageview', '/member' + window.location.pathname]);
Note that the /member+ part is now within the array, not outside of it.
What you were doing was passing the _trackPageview function name without a second parameter to be its argument (which, by default, tracks the pageview as location.pathname+location.search, and then passing a string /member+window.location.pathname to the array, which did nothing.
Passing the custom URL as a 2nd item in an array will make it work just fine.
Aside from the fact that you probably shouldn't use the same URL structure for goal tracking in Google Analytics, I can suggest a couple of ways to solve the problem. Note that this doesn't address the alias-tracking question you asked, but offers some alternatives.
1. Append a querystring parameter to goal pages for members or guests
Bit of a hack, but it should be trivial to append a ?guest=true param if your users are not logged in. This would be a minor change that should not affect your business logic or website operation.
You can then set different goals in GA that look for the success page with or without the URL param.
2. Set custom variables in Google Analytics for members and guests
This is the more correct solution.
Use session-level custom variables to distinguish different visitor experiences across sessions.
For example, if your website offers users the ability to login, you can use a custom variable scoped to the session level for user login status. In that way, you can segment visits by those from logged in members versus anonymous visitors.
http://code.google.com/apis/analytics/docs/tracking/gaTrackingCustomVariables.html#sessionLevel
Then you can segment your goal starts and completions using your advanced segments, segmenting on user login status:
http://www.lunametrics.com/blog/2010/10/07/visitor-signed-in/