Issue - Error
I get this error,
Error: CSE.js:130 Uncaught ReferenceError: google is not defined
Issue - Description
However, if I use the chrome console in web tools, if google.search.... is used, it works.
not sure why google isn't loading in the context of my code, please help.
Code
// Generate CSE Script
let scr = document.createElement('script'),
head = document.head || document.getElementsByTagName('head')[0];
scr.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cse_cx;
scr.async = false; // optionally
head.insertBefore(scr, head.firstChild);
// Get Results Element
let element = google.search.cse.element.getElement('searchresults-only0');
after code executes, etc.
doing this will work
You might want to use the Search Element initialization callback in this case. Check out https://developers.google.com/custom-search/docs/element#init-callback
So adding a "Delay" works,
I wrapped my code with a setTimeout(function(){ /*CODE HERE*/ }, 1000); after dynamically injecting the script.
Related
I am adding ZohosalesIQ to the CookieBot Prior Consent widget on w WP install.
This script given by zoho is
<script type="text/javascript" data-cookieconsent="statistics">
var $zoho = [];
var $zoho = $zoho || {};
$zoho.salesiq = $zoho.salesiq || {
widgetcode: "1c636a8a8d8e3410b7e579760898b7768f3cb213adb21970788a3891735df801800b6e4a1385c37b0f792b9ee54ce",
values: {},
ready: function() {}
};
var d = document;
s = d.createElement("script");
s.type = "text/javascript";
s.id = "zsiqscript";
s.defer = true;
s.src = "https://salesiq.zoho.eu/widget";
t = d.getElementsByTagName("script")[0];
t.parentNode.insertBefore(s, t);
d.write("<div id='zsiqwidget'></div>");
</script>
I am supposed to be adding <script type="text/plain" data-cookieconsent="statistics">
to the script tag to enable prior consent on cookies created by this script however, when I add this it breaks and fails to load.
Console is empty but the page renders as a white page after pre-load. When I add the code with the jaavscript type tag, it works fine.
I've tried popping itto a call back function but no joy :(
Any pointers would be great.
If the script tag is using the deprecated JavaScript function “document.write” it might cause the problem you have described above because using this function the script is loaded synchronously and it will then clear the window content (generates blank page).
To prevent this issue please make sure that the script is loaded asynchronously since the Cookiebot triggers all scripts asynchronously (i.e. to wait for the visitor’s consent) in order to work properly.
You need rewrite it to use a different approach e.g. “document.write = function(node) {document.body.insertAdjacentHTML(‘beforeend’, node);}”
We have a custom searchbar on our website and I noticed that sometimes (9/10 times) the JS will throw this error, which forces the content that you searched for to not render
www.googleapis.com/customsearch/v1element?key=AIzaSyCVAXiUzRYsML1Pv6RwSG1gu…oogle.com&callback=google.search.Search.apiary####&nocache=1446053383742:2
Uncaught TypeError: google.search.Search.apiary#### is not a function
Search page when error is thrown:
Search page with error truncated/resolved
But if I were to refresh, or research, this error is trumped and will render all of my searches. After looking through the file, I found out the google.search.Search.apiary#### that they are referring to is only mentioned once. So I believe that this error is truncating the entire file when it does show up. What could be causing this, what would be some options for fixing it?
Alright, I stumbled upon an answer:-
After doing some more research, I found that this user on Google Forums also has the same issue.
To put it simply, the way it works is you use a <script> to generate your searchbar.
You have this function + html element for your search bar
<script>
(function() {
var cx = '###';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchbox-only resultsUrl="/search-results"></gcse:searchbox-only>
So we generated the bar in our <div class="header"> which is a HAML element, as a part of a template. So it was always loaded within every header. Since we have 10 pages, this same script was generated 1 time per page.
Our Google CSE is made to search and then redirect to the url /search-results where it generates the results.
To generate the results, you needed this function and HTML
<script>
(function() {
var cx = '###';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
Which is the same as the one being loaded in our Header.
With this set up, the results page would call that <script> twice when loading in, and cause the JS to break. So after removing the <script> loading the results, it stopped throwing the error.
To put it brief, just make sure you aren't calling the same function twice on your results page, and it should clear up the Uncaught TypeError.
Don't. Repeat. Yourself
--ether
In my case I accidentally had the form and script for the Google Custom Search repeated twice on the same page. Once the second lot was removed it stopped giving the error.
I have this JS:
<script type="text/javascript">
var aaascript = document.createElement('script'); aaascript.type = 'text/javascript';
aaascript.src = ('https:' == document.location.protocol ? 'https://xxx' : 'http://xxx') + '/aaa.js';
var aaas = document.getElementsByTagName('script')[0]; aaas.parentNode.insertBefore(aaascript,aaas);
callthis('somevalue');
</script>
this code generates a script tag and inserts it to the page. in the script aaa.js is the function callthis. but when I call the function there is this error:
Uncaught ReferenceError: callthis is not defined (anonymous function)
what goes wrong here?
The script tag is being created but the script is then loaded from the server. callthis() is being called in between these two events; that is, before the script is fully loaded, and so the method doesn't exist.
Use the .onload event of the script tag to delay calling callthis() until the script is fully loaded, as documented here.
Hello I'm trying to add jQuery to my Userscript that I'm creating.
I've tried:
$ = jQuery = window.jQuery;
Doesn't work $ is undefined. My other choice is:
$ = unsafeWindow.jQuery;
Which works and all, but I receive this error:
Unexpected token e
That's not even part of my code, it points to something on the website. However, I noticed that the website I'm creating a userscript for uses this:
jQuery.noConflict();
Is that the cause of this? And I can't import the jQuery library because I'm trying to make custom emotes for a shoutbox which uses XMLHttpRequests(AJAX) and it prevents the chat from working when I load an external library.
I've been trying to fix this for 6 hours and I'm getting nowhere. I'd probably turn to just using DOM if nothing works =/.
Thank you for all that helped and if you need any information from me I'll gladly share it.
I just looked at another userscript and this is the solution!
(function wrapper(window, injectNeeded, undefined) {
// Script injection if needed.
if (injectNeeded) {
var script = document.createElement('script');
script.textContent = '(' + wrapper + ')(window, false)';
document.body.appendChild(script);
document.body.removeChild(script);
return;
}
var $,
jQuery;
$ = jQuery = window.jQuery;
console.log($('a').length + "links on this page.");
})(this.unsafeWindow || window, window.chrome ? true : false);
Source: https://raw.github.com/cletusc/Userscript--Twitch-Chat-Emotes/master/script.user.js#bypass=true
[cross-posted on Google Products Forum http://productforums.google.com/d/topic/analytics/ZrB14a-6gqI/discussion ]
I am using the following code at http://www.cs.bris.ac.uk/Research/Algorithms/
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_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);
})();
</script>
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var myTracker=_gat._getTrackerByName();
_gaq.push(['myTracker._trackEvent', category , action ]);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
which I just copied directly from http://support.google.com/analytics/bin/answer.py?hl=en&answer=1136920 .
However, it doesn't actually seem to report any clicks on the links where I have added onClick="recordOutboundLink(this, 'Outbound Links', 'Postdoc advert');return false;", for example. I have seen a number of complaints about this online but I haven't found a solution that works.
What am I doing wrong?
P.S. The closest related online complaint seems to be http://productforums.google.com/forum/#!topic/analytics/4oPBJEoZ8s4 which just claims the code is broken.
Here's what I'm using, which has been working for me. I'm using jQuery to add the onclick handler to any link with a class of "referral", but I'd expect adding it directly in the HTML to work as well.
$(function() {
$('.referral').click(function() {
_gaq.push(['_trackEvent', 'Referral', 'Click', this.href]);
setTimeout('document.location = "' + this.href + '"', 100);
return false;
});
});
edit: I believe your syntax for invoking a tracker by name is wrong. Since you aren't using a named tracker when you set up tracking at page load, you shouldn't try to name it later either. See the documentation for _gaq.push.
More precisely:
The var myTracker declaration is unused, so you can just delete that line. Variables declared within the scope of recordOutboundLink aren't visible when other functions, such as _gaq.push, are running, so it can't be relevant.
You should simply use '_trackEvent' instead of 'myTracker._trackEvent'.
You can also try this automated external link script
Set a longer timeout 2 seconds maybe, as it takes a certain amout of time for the _gaq.push to actually push to the server, and 100 milliseconds isnt long enough for it to send (the push gets cancelled as soon as the document.location changes). Unless _gaq.push uses a blocking call (doesnt execute the next line till the push is complete), but i dont think that is the case i think most of that uses asynchronous requests.