javascript / jquery - google custom search api - functions triggering twice - javascript

I'm using the code from the google search API along with my own jquery function to do a simple log to the console, and I noticed the jquery functions are being triggered twice. In addition, javascript errors are being thrown (this happens even on Google's example page).
Here's my code:
<script type="text/javascript">
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function() {
var customSearchControl = new google.search.CustomSearchControl('000638822871137547098:_xxgiq7wt_k');
var linkTarget = "frame";
//customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
//customSearchControl.draw('cse');
// Use "mysite_" as a unique ID to override the default rendering.
google.search.Csedr.addOverride("mysite_");
customSearchControl.setLinkTarget(linkTarget)
// Draw the Custom Search Control in the div named "CSE"
customSearchControl.draw('cse');
$('.gsc-search-button').click(function(){
console.log('click');
})
// Execute an initial search
//customSearchControl.execute("ajax");
}, true);
</script>
and here's the javascript error that occurs:
Unsafe JavaScript attempt to access frame with URL about:blank from frame with URL http://www.google.com/cse?q=x&client=google-coop&hl=en&r=s&cx=000638822871137547098%3A_xxgiq7wt_k&oe=UTF-8&ie=UTF-8&format=n4&ad=n0&adsafe=high&nocache=1319551264502&fexp=20606&num=0&safe=off&output=uds_ads_only&source=gcsc&v=3&adext=as1%2Csr1&rurl=http%3A%2F%2Flocalhost%3A8888%2F#slave-1-1. Domains, protocols and ports must match.
Lastly, here's the example from google code:
http://code.google.com/apis/customsearch/docs/js/rendering.html#_intro_CSC
How do I resolve these errors and fix the double click issue?

Looks like I was going about this the wrong way - to do the things I want to do, it's better to use the JSON Custom Search API - with documentation available here:
http://code.google.com/apis/customsearch/v1/overview.html

Related

Error when using YUI3: "Y.QueryString.parse is not a function"

I'm building a Squarespace page, and I want to have an outgoing link on the page whose query parameters are set according to query parameters on the page itself. Since Squarespace embeds YUI3 in every site automatically, I'm trying to use that (even though I have more experience with jquery).
Example: The page is loaded as http://example.com/page/?email=foo#bar.com. I have a link on the page that goes to http://another.example.com/page which should be modified to go to http://another.example.com/page?address=foo#bar.com.
The following code does exactly what I need when I paste it in the browser console:
var MyButton = Y.all('a[href="http://another.example.com/page"]');
var QueryString = Y.QueryString.parse(window.location.search.substring(1));
MyButton.setAttribute('href','http://another.example.com/page?address=' + QueryString.email);
However, when I put that code in the page source, then when the page loads, the following error appears in the console: Uncaught TypeError: Y.QueryString.parse is not a function
My current theory is that YUI3 loads asynchronously in pieces, and this code runs at a point when Y.all is available but Y.QueryString.parse is not... is that right? What would be the best solution to this?
Yui3 is indeed built around asychonous modules loading, in this case you miss the querystring module.
You need to wrap your code with a Y.use call:
Y.use('querystring', function(Y) {
var MyButton = Y.all('a[href="http://another.example.com/page"]');
var QueryString = Y.QueryString.parse(window.location.search.substring(1));
MyButton.setAttribute('href', 'http://another.example.com/page?address=' + QueryString.email);
});

How to tell if Google Analytics is loaded

I make a lot of javascript widgets. As part of these widgets, we often use Google Analytics to track actions within the widget. Simplified, what I do is:
var setupGA = function(){ window._gaq.push(['_setAccount', 'UA-###']); };
if(window._gaq){
setupGA();
} else {
this.loadScript(GOOGLE_ANALYTICS_PATH, function(){
var waitga = setInterval(function(){
if(window._gaq){
clearInterval(waitga);
setupGA();
}
}, 500);
});
}
Where GOOGLE_ANALYTICS_PATH is my local path to the file and loadScript is a custom method to load the script and execute a callback.
With Google updating their analytics library (now analytics.js), old methods of ensuring that the analytics library has been loaded no longer work. The example code for google analytics helpfully provides a global ga object, but this object can have a custom name. With the old queue to check, I'm wondering how best I can check for the existance of either analytic.js or ga.js versions of google analytics (I Can skip the very old Urchin Tracking types).
It must be something like:
var setupGA = function(){ window._gaq.push(['_setAccount', 'UA-###']); };
if(window._gaq && !window.**ga**){
setupGA();
} else {
this.loadScript(GOOGLE_ANALYTICS_PATH, function(){
var waitga = setInterval(function(){
//_gaq will always be loaded for now
if(window._gaq){
clearInterval(waitga);
setupGA();
}
}, 500);
});
}
Where the ga is whatever global element I can check. I suppose thats what I'm looking for
Answered my own question with a little more exploration.
With the new Universal Analytics platform, it seems that a window level variable is created. That variable is called GoogleAnalyticsObject. This object will give you the variable name created to house the Universal Analytics Object
EX: Using (window,document,'script','//www.google-analytics.com/analytics.js','ga'); will return "ga"
EX: Using (window,document,'script','//www.google-analytics.com/analytics.js','notGA'); will return "notGA"
You can then use this variable to pull the Analytics object:
window[window.GoogleAnalyticsObject]
Another approach is to open the browser console and look for the tracking request in the network tab. If the tracking code isn't loading successfully, you won't see a tracking request being sent to Google.
With Universal Analytics (analytics.js), look for a request to www.google-analytics.com/collect
With Legacy code (ga.js or urchin.js), look for a request for __utm.gif
If your browser uses a script blocking plugin like NoScript, the tracking code won't run unless you allow scripts from www.google-analytics.com

Call JavaScript function on a page automatically with Chrome?

When I load a particular webpage, I'd like to call a Javascript function that exists within their page. I could use a bookmarklet with javascript:TheFunction();, but I'd like to know if there's an easier way to do it, either with a Chrome extension or otherwise.
With chrome, you can either install a grease monkey script directly or get the Blank Canvas script handler plugin (the latter of which I use).
Chrome extensions run in a sandbox so you cannot call a function directly from the webpage code how you want. you either have to use javascript:fuction(); and set document.location, or you can create script elements on the page with a callback to your own extension. check out how this guy did it:
https://convore.com/kynetx/kbx-writing-durable-code/
i am refering to this post, and the one above and below it specifically
var anewscript = document.createElement("script");
anewscript.type = 'text/javascript';
anewscript.innerHTML=' callback_tmp= function (mydata){ ' +
' document.getElementById("someElement").onclick(mydata);' +
'}';
document.getElementsByTagName("head")[0].appendChild(anewscript);
An alternative option is to modify the javascript function to make it globally accessible from the [Chrome] debug console.
Change the function from for example
function foo(data)
to
foo = function(data)
then using the debug console, call the method with the attributes required
data = {my: "data"}
foo(data)

Getting an Odd Error using Javascript/jQuery

Trying to select the following link in html:
Nodequeue
with this Javascript:
jQuery("a:contains('Nodequeue')").trigger("click");
And I am receiving this error message:
Javascript console (:1): Unsafe JavaScript attempt to access frame with URL http://cdn.nprove.com/cpma/p/1/2/e/b/12ebf3bc368ry3ra.html?npuid=1310010225&rurl=&id=cpma-2n7eypbvio581300288437193&null=&r=366424962878227 from frame with URL http://www.benzinga.com/analyst-ratings/analyst-color/11/07/1742957/the-beef-stops-here. Domains, protocols and ports must match.
Any idea what might cause this?
I created a
JSFiddle of your code which you can look at and notice that in the console your error doesn't come up in Chrome 12 or FireFox 5. I'm not sure what version of jQuery you are using that is causing that or your DOM situation that may be triggering that error, however, try this potential fix:
(function(window, $) {
$.fn.triggerAnchor = function() {
return this.each(function(e) {
var href = $(this).attr('href');
window.location.href = href;
return false;
});
};
})(this, this.jQuery);
Then use with:
$("a:contains('Nodequeue')").triggerAnchor();
I don't think jQuery triggers anchors, and it certaintly doesn't trigger native click events. This is the closest thing I can think of to emulate that behavior.
You can see it 'working' here
Explanation of the code:
The code is simply a jQuery plugin that looks at the href attribute of anchor and sets the window location to that value. I wrote in the typical pattern of a wrapped closure to localize references to window and jQuery. I'm allowing you to call this on multiple anchors, but I'm assuming the average user would only need to run this once.
That error usually means you are making a javascript request from one frame to another. In this case, is the link in an iframe, or is jquery running in an iframe?

How to code firefox extension which run javascript code in the page's context like firebug does

I know that for safety reasons that this is not easy to achieve, however there would be a way to do so as firebug does...
Please help, would like to invoke some script in the page's context to achieve some effect...
Basically, I would like to achieve two functionality:
1. add jQuery to any web page automatically if not already exist.
2. when open certain address, call a method of that page to auto notify the server. (an ajax functionality of the page)
I have tried to inject on the body, no luck.
tried to get the window object, which however do not have access to call the function.
Will try to change the location to something like: javascript:alert('test inject');
Many thx.
OK, after reading some official documentation and the GreaseMonkey's source, I get the following method which basically works for me.
Hope it will save sb's hour:
var appcontent = document.getElementById("appcontent"); // browser
if (appcontent) {
appcontent.addEventListener("DOMContentLoaded", function (evnt) {
var doc = evnt.originalTarget;
var win = doc.defaultView;
var unsafeWin = win.wrappedJSObject;
// vote.up is the function on the page's context
// which is take from this site as example
unsafeWin.vote.up(...);
}, true);
}
}
Greasemonkey does that. If you are developing your own extension with similar functionality, you can use Components.utils.evalInSandbox.

Categories