jQuery.noConflict(); for userscript - javascript

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

Related

Javascript Google Custom search engine

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.

Cookiebot Cookie Consent Script

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);}”

Intel XDK JavaScript gives out an error of 'alert is not defined (w117)

I m a newbie to programming in JS, i though of giving a try in intel XDk.
I browsed some videos and according to one tutorial, i followed the exact same steps as he did,
But unfortunately, he got the script in emulator working while mine got stuck with a problem of `alert is not defined (W117)' but he didn't got that error,.
My JS code as follows:
/*jshint browser:true */
/*global $ */(function()
{
"use strict";
/*
hook up event handlers
*/
function register_event_handlers()
{
/* button #submit */
$(document).on("click", "#submit", function(evt)
{
/* your code goes here */
var name = document.getElementById('name').value;
var place = document.getElementById('place').value;
var job = document.getElementById('job').value;
var gender = document.getElementById('gender').value;
var reason = document.getElementById('reason').value;
var text = name + place + job + gender + reason ;
alert(text);
return false;
});
}
document.addEventListener("app.Ready", register_event_handlers, false);
})();
Any help is appreciated..
I don't have your full JS code and cannot find an 'app.Ready' event (which is being run on load looks like). To perform check based on jQuery 'ready' event just use below code:
$(document).on("click", "#submit", function(evt) {
var name = document.getElementById('name').value;
var place = document.getElementById('place').value;
var job = document.getElementById('job').value;
var gender = document.getElementById('gender').value;
var reason = document.getElementById('reason').value;
var text = name + place + job + gender + reason;
alert(text);
return false;
});
With the 3900 (and later) releases of the XDK there is a known issue where the alert() (and related) functions no longer work inside the Simulate tab. This was due to an upgrade of the version of Chromium that is built into the node-webkit image that underlies the XDK. At this time there is no workaround, other than to use the Cordova dialogs plugin as an alternative.
Note that in some WebViews (the runtime that your Cordova app runs in when it runs on a real device) the alert() function does not exist, since it is an optional feature and not required. Keep in mind that your Cordova app does not actually run in a browser, it runs in an embedded runtime that feels a bit like a browser, but it's not. Just like Node.js apps have a JavaScript runtime engine, so do WebViews, but neither runtime is hosted within a browser.
In general, using the alert() function is not a good option for a real app.

Adding Google Analytics to Adobe Air HTML/Javascript App

I am attempting to add google analytics tracking to an Adobe Air app created with HTML and javascript.
I have tried adding the ga.js file and using it like I would in a webpage:
<script type="text/javascript" src="lib/js/ga.js"></script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-********-1");
pageTracker._initData();
pageTracker._trackPageview('/test');
</script>
But this doesn't seem to register anything on the analytics dashboard.
Have also tried using the GA for flash actionscript library but I can't seem to create an instance of the GATracker as it needs a DisplayObject?
EDIT
using the information from grapefrukt I tried the following:
air.Sprite = window.runtime.flash.display.Sprite;
air.GATracker = window.runtime.com.google.analytics.GATracker;
var tracker = new air.GATracker( new air.Sprite(), "UA-XXXXXXX-X", "AS3", false );
but I get the following error:
TypeError: Error #1009: Cannot access a property or method of a null object reference
NOTE: I originally misread your question to be about how to use gaforflash, but I'll post this anyway since I've already typed it up and it might be of some use.
You can the constructor whatever DisplayObject you like, normally you'd use your document class, but anything will work. As far as I can understand it's only really used for displaying debug info.
var tracker:AnalyticsTracker = new GATracker( new Sprite, "UA-XXXXXXX-X", TrackerMode.AS3, false );
Setting the TrackerMode to AS3 let's the flash communicate directly with the tracking servers, so you don't need the javascript from google's servers.
I can't help you with the communication between js/as3, but that should be fairly easy.
Probably not useful to the OP, but just spent the whole day working around this so hopefully my solution will save someone else that time.
So the reason the ga.js code can't be used directly from an AIR app written in javascript is that AIR won't set the cookie for pages that are stored within the application itself. To work around this, I downloaded ga.js to the application and modified it so that it doesn't rely on the document.cookie function.
In the application, I have:
<script type="text/javascript">
var cookies = {};
document.__defineSetter__('_cookie', function(c) {
var epos = c.indexOf('=');
var spos = c.indexOf(';', Math.max(0, epos));
if (epos == -1 || spos == -1) { return; }
var name = c.substring(0, epos);
var value = c.substring(epos + 1, spos);
cookies[name] = value;
});
document.__defineGetter__('_cookie', function() {
var a = [];
for (var name in cookies) {
a.push(name + '=' + cookies[name]);
}
return a.join('; ');
});
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-1']);
_gaq.push(['_trackPageview', path])
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
// custom GA code which uses document._cookie instead of
// document.cookie
ga.src = 'js/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
Ideally, we'd be able to override the cookie method, but unfortunately, it doesn't seem possible in webkit as implemented for AIR. So in ga.js, I replaced all instances of J.cookie with J._cookie. Once that's done, ga.js should believe that it's writing cookies and function normally.
In the interest of full disclosure, I actually access the above analytics code through an iframe, but since ga.js is being served locally, I suspect it's no longer necessary and didn't want to complicate the solution by adding the bridge logic.

Loading scripts dynamically

I'm loading a few YUI scripts dynamically in my code in response to an Ajax request. The DOM and the page is fully loaded when the request is made - it's a response for an user event.
I add the <scripts> tag to head as children, but I stumbled in a few problems:
I add two YUI scripts hosted at the Yahoo! CDN and an inlined script of my own responsible for creating object, adding event listeners and rendering the YUI widgets. But I when my script run the YUI scripts are not loaded yet giving me errors and not running as I expect.
There's a way to only run my script (or define a function to be run) when YUI scripts are fully loaded?
Have you tried an onload event?
Edited:(thanks Jamie)
var script = document.createElement("script");
script.type = "text/javascript";
script.src = src;
//IE:
if(window.attachEvent && document.all) {
script.onreadystatechange = function () {
if(this.readyState === "complete") {
callback_function(); //execute
}
};
}
//other browsers:
else {
script.onload = callback_function; //execute
}
document.getElementsByTagName("head")[0].appendChild(script);
If you're using YUI 2.x I highly recommend using the YUI Get utility, as it's designed to handle just this sort of a problem.
If you are loading multiple individual script files from the Yahoo! CDN, you'll need to makes sure both are loaded before executing your dependent code. You can avoid this using the combo handler. See the Configurator to get what the script url should be to load both/all needed YUI files from one url.
http://developer.yahoo.com/yui/articles/hosting/
With that in mind, assuming you must load the YUI files asynchronously, you should use an onload/onreadystatechange handler as noted by digitalFresh.
I would recommend the following pattern, however:
(function (d) {
var s = d.createElement('script'),
onEvent = ('onreadystatechange' in s) ? 'onreadystatechange' : 'onload';
s[onEvent] = function () {
if (("loaded,complete").indexOf(this.readyState || "loaded") > -1) {
s[onEvent] = null;
// Call your code here
YAHOO.util.Dom.get('x').innerHTML = "Loaded";
}
};
// Set the src to the combo script url, e.g.
s.src = "http://yui.yahooapis.com/combo?2.8.1/...";
d.getElementsByTagName('head')[0].appendChild(s);
})(document);
You could use a setTimeout() to run some function that just checks if it's loaded - check something like
if (typeof YUI_NAMESPACED_THING !== "undefined") runCode()
EDIT Thanks, CMS
If I understand this correctly, your ajax response with this:
<script href="yui-combo?1"></script>
<script href="yui-combo?2"></script>
<p>some text here</a>
<script>
// using some of the components included in the previous combos
// YAHOO.whatever here...
</script>
If this is the case, this is a clear case in which you should use dispatcher plugin. Dispatcher will emulate the browser loading process for AJAX responses. Basically it will load and execute every script in the exact order.
Best Regards,
Caridy

Categories

Resources