Cannot get value of certain cookies - Javascript - javascript
I have been using this code found on Github to collect some UTM/other URL parameters.
I have been able to successfully save the parameters in a cookie, and pass those values into a hidden input form.
This code is loaded through Google Tag Manager on every page of the website.
Scenario:
-The cookie sessions exist on every page of the site as expected.
-The main website is on a non-secure HTTP connection (http://www.example.com).
-A secure page exists on the subdomain. (https://www.subdomain.example.com).
Problem: On the secure, subdomain page, I cannot get the values from none of the UTM cookies. I can get the values from the VISITORS, IREFERRER, LREFERRER, and ILANDINGPAGE cookies, but not from the UTM cookies.
Here is the code that I am using:
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function(){
var _uf = _uf || {};
_uf.domain = ".exampledomain.com";
var UtmCookie;
UtmCookie = (function() {
function UtmCookie(options) {
if (options == null) {
options = {};
}
this._cookieNamePrefix = '_uc_';
this._domain = options.domain;
this._sessionLength = options.sessionLength || 1;
this._cookieExpiryDays = options.cookieExpiryDays || 365;
this._additionalParams = options.additionalParams || [];
this._utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
this.writeInitialReferrer();
this.writeLastReferrer();
this.writeInitialLandingPageUrl();
this.setCurrentSession();
if (this.additionalParamsPresentInUrl()) {
this.writeAdditionalParams();
}
if (this.utmPresentInUrl()) {
this.writeUtmCookieFromParams();
}
return;
}
UtmCookie.prototype.createCookie = function(name, value, days, path, domain, secure) {
var cookieDomain, cookieExpire, cookiePath, cookieSecure, date, expireDate;
expireDate = null;
if (days) {
date = new Date;
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expireDate = date;
}
cookieExpire = expireDate != null ? '; expires=' + expireDate.toGMTString() : '';
cookiePath = path != null ? '; path=' + path : '; path=/';
cookieDomain = domain != null ? '; domain=' + domain : '';
cookieSecure = secure != null ? '; secure' : '';
document.cookie = this._cookieNamePrefix + name + '=' + escape(value) + cookieExpire + cookiePath + cookieDomain + cookieSecure;
};
UtmCookie.prototype.readCookie = function(name) {
var c, ca, i, nameEQ;
nameEQ = this._cookieNamePrefix + name + '=';
ca = document.cookie.split(';');
i = 0;
while (i < ca.length) {
c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
i++;
}
return null;
};
UtmCookie.prototype.eraseCookie = function(name) {
this.createCookie(name, '', -1, null, this._domain);
};
UtmCookie.prototype.getParameterByName = function(name) {
var regex, regexS, results;
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
regexS = '[\\?&]' + name + '=([^&#]*)';
regex = new RegExp(regexS);
results = regex.exec(window.location.search);
if (results) {
return decodeURIComponent(results[1].replace(/\+/g, ' '));
} else {
return '';
}
};
UtmCookie.prototype.additionalParamsPresentInUrl = function() {
var j, len, param, ref;
ref = this._additionalParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
if (this.getParameterByName(param)) {
return true;
}
}
return false;
};
UtmCookie.prototype.utmPresentInUrl = function() {
var j, len, param, ref;
ref = this._utmParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
if (this.getParameterByName(param)) {
return true;
}
}
return false;
};
UtmCookie.prototype.writeCookie = function(name, value) {
this.createCookie(name, value, this._cookieExpiryDays, null, this._domain);
};
UtmCookie.prototype.writeAdditionalParams = function() {
var j, len, param, ref, value;
ref = this._additionalParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
value = this.getParameterByName(param);
this.writeCookie(param, value);
}
};
UtmCookie.prototype.writeUtmCookieFromParams = function() {
var j, len, param, ref, value;
ref = this._utmParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
value = this.getParameterByName(param);
this.writeCookie(param, value);
}
};
UtmCookie.prototype.writeCookieOnce = function(name, value) {
var existingValue;
existingValue = this.readCookie(name);
if (!existingValue) {
this.writeCookie(name, value);
}
};
UtmCookie.prototype._sameDomainReferrer = function(referrer) {
var hostname;
hostname = document.location.hostname;
return referrer.indexOf(this._domain) > -1 || referrer.indexOf(hostname) > -1;
};
UtmCookie.prototype._isInvalidReferrer = function(referrer) {
return referrer === '' || referrer === void 0;
};
UtmCookie.prototype.writeInitialReferrer = function() {
var value;
value = document.referrer;
if (this._isInvalidReferrer(value)) {
value = 'direct';
}
this.writeCookieOnce('referrer', value);
};
UtmCookie.prototype.writeLastReferrer = function() {
var value;
value = document.referrer;
if (!this._sameDomainReferrer(value)) {
if (this._isInvalidReferrer(value)) {
value = 'direct';
}
this.writeCookie('last_referrer', value);
}
};
UtmCookie.prototype.writeInitialLandingPageUrl = function() {
var value;
value = this.cleanUrl();
if (value) {
this.writeCookieOnce('initial_landing_page', value);
}
};
UtmCookie.prototype.initialReferrer = function() {
return this.readCookie('referrer');
};
UtmCookie.prototype.lastReferrer = function() {
return this.readCookie('last_referrer');
};
UtmCookie.prototype.initialLandingPageUrl = function() {
return this.readCookie('initial_landing_page');
};
UtmCookie.prototype.incrementVisitCount = function() {
var cookieName, existingValue, newValue;
cookieName = 'visits';
existingValue = parseInt(this.readCookie(cookieName), 10);
newValue = 1;
if (isNaN(existingValue)) {
newValue = 1;
} else {
newValue = existingValue + 1;
}
this.writeCookie(cookieName, newValue);
};
UtmCookie.prototype.visits = function() {
return this.readCookie('visits');
};
UtmCookie.prototype.setCurrentSession = function() {
var cookieName, existingValue;
cookieName = 'current_session';
existingValue = this.readCookie(cookieName);
if (!existingValue) {
this.createCookie(cookieName, 'true', this._sessionLength / 24, null, this._domain);
this.incrementVisitCount();
}
};
UtmCookie.prototype.cleanUrl = function() {
var cleanSearch;
cleanSearch = window.location.search.replace(/utm_[^&]+&?/g, '').replace(/&$/, '').replace(/^\?$/, '');
return window.location.origin + window.location.pathname + cleanSearch + window.location.hash;
};
return UtmCookie;
})();
var UtmForm, _uf;
UtmForm = (function() {
function UtmForm(options) {
if (options == null) {
options = {};
}
this._utmParamsMap = {};
this._utmParamsMap.utm_source = options.utm_source_field || 'USOURCE';
this._utmParamsMap.utm_medium = options.utm_medium_field || 'UMEDIUM';
this._utmParamsMap.utm_campaign = options.utm_campaign_field || 'UCAMPAIGN';
this._utmParamsMap.utm_content = options.utm_content_field || 'UCONTENT';
this._utmParamsMap.utm_term = options.utm_term_field || 'UTERM';
this._additionalParamsMap = options.additional_params_map || {};
this._initialReferrerField = options.initial_referrer_field || 'IREFERRER';
this._lastReferrerField = options.last_referrer_field || 'LREFERRER';
this._initialLandingPageField = options.initial_landing_page_field || 'ILANDPAGE';
this._visitsField = options.visits_field || 'VISITS';
this._addToForm = options.add_to_form || 'all';
this._formQuerySelector = options.form_query_selector || 'form';
this.utmCookie = new UtmCookie({
domain: options.domain,
sessionLength: options.sessionLength,
cookieExpiryDays: options.cookieExpiryDays,
additionalParams: Object.getOwnPropertyNames(this._additionalParamsMap)
});
if (this._addToForm !== 'none') {
this.addAllFields();
}
}
UtmForm.prototype.addAllFields = function() {
var fieldName, param, ref, ref1;
ref = this._utmParamsMap;
for (param in ref) {
fieldName = ref[param];
this.addFormElem(fieldName, this.utmCookie.readCookie(param));
}
ref1 = this._additionalParamsMap;
for (param in ref1) {
fieldName = ref1[param];
this.addFormElem(fieldName, this.utmCookie.readCookie(param));
}
this.addFormElem(this._initialReferrerField, this.utmCookie.initialReferrer());
this.addFormElem(this._lastReferrerField, this.utmCookie.lastReferrer());
this.addFormElem(this._initialLandingPageField, this.utmCookie.initialLandingPageUrl());
this.addFormElem(this._visitsField, this.utmCookie.visits());
};
UtmForm.prototype.addFormElem = function(fieldName, fieldValue) {
var allForms, firstForm, form, i, len;
if (fieldValue) {
allForms = document.querySelectorAll(this._formQuerySelector);
if (allForms.length > 0) {
if (this._addToForm === 'first') {
firstForm = allForms[0];
firstForm.insertBefore(this.getFieldEl(fieldName, fieldValue), firstForm.firstChild);
} else {
for (i = 0, len = allForms.length; i < len; i++) {
form = allForms[i];
form.insertBefore(this.getFieldEl(fieldName, fieldValue), form.firstChild);
}
}
}
}
};
UtmForm.prototype.getFieldEl = function(fieldName, fieldValue) {
var fieldEl;
fieldEl = document.createElement('input');
fieldEl.type = "hidden";
fieldEl.name = fieldName;
fieldEl.value = fieldValue;
return fieldEl;
};
return UtmForm;
})();
_uf = window._uf || {};
window.UtmForm = new UtmForm(_uf);
/*
var USOURCE = jQuery("input[name='USOURCE']").val();
var UMEDIUM = jQuery("input[name='UMEDIUM']").val();
var UCAMPAIGN = jQuery("input[name='UCAMPAIGN']").val();
var UCONTENT = jQuery("input[name='UCONTENT']").val();
var UTERM = jQuery("input[name='UTERM']").val();
var IREFERRER = jQuery("input[name='IREFERRER']").val();
var LREFERRER = jQuery("input[name='LREFERRER']").val();
var ILANDPAGE = jQuery("input[name='ILANDPAGE']").val();
var VISITS = jQuery("input[name='VISITS']").val();
console.log(USOURCE);
console.log(UMEDIUM);
console.log(UCAMPAIGN);
console.log(VISITS);
*/
jQuery('#saveProfile').on('click', function(e){
console.log('Click submitted');
e.preventDefault();
// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}
var readCampaign = readCookie_uc_utm_campaign
var FirstName = jQuery('#ownerInformation_FirstName').val();
var LastName = jQuery('#ownerInformation_LastName').val();
var USOURCE = getCookie('_uc_utm_source');
console.log(USOURCE);
var UMEDIUM = getCookie('_uc_utm_medium') || '';
var UCAMPAIGN = getCookie('_uc_utm_campaign') || '';
var UCONTENT = getCookie('_uc_utm_content') || '';
var UTERM = getCookie('_uc_utm_term') || '';
var IREFERRER = jQuery("input[name='IREFERRER']").val();
var LREFERRER = jQuery("input[name='LREFERRER']").val();
var ILANDPAGE = jQuery("input[name='ILANDPAGE']").val();
var VISITS = jQuery("input[name='VISITS']").val();
dataLayer.push({'event':FirstName,'event_cat':LastName,'event_action':USOURCE,'event_label':VISITS});
jQuery.ajax({
url: "https://script.google.com/macros/s/googleappsscript/exec",
data: {'FirstName':FirstName,'LastName':LastName,'USOURCE':USOURCE, 'UMEDIUM':UMEDIUM, 'UCAMPAIGN':UCAMPAIGN, 'UCONTENT':UCONTENT, 'UTERM':UTERM, 'IREFERRER':IREFERRER, 'LREFERRER':LREFERRER, 'VISITS':VISITS},
type: "POST",
dataType: "json"
});
});
})
</script>
Any help or guidance would be greatly appreciated.
Thanks,
Blaine
The reason why cookies are restricted by domains like this is to prevent security breaches.
See this answer for the way around it: Cross-Domain Cookies
Related
Multiple name capture from sign up form
I had some code created to convert a 3rd party form to jQuery AJAX with a custom redirect. On the redirect page the users name from the form was captured. The issue is that I can only capture the name once. If I try to duplicate the code to show the name multiple times it doesn't work. Would much appreciate the help! ------Javascript for the submit button------ window.CFS = window.CFS || {}; (function () { "use strict"; CFS.msgPleaseWait = 'Please wait...'; CFS.msgRedirect = 'Redirecting...'; CFS.nameField = ''; CFS.nameFromSubmitField = ''; CFS.redirectTo = ''; CFS.submitButtonText = ''; CFS.submitHandler = function(form) { var $form = $(form); var dataToPost = $form.serialize(); var urlToPostTo = $form.attr("action"); var $submitButton = $("input[type='submit']", $form); CFS.submitButtonText = $submitButton.val(); CFS.disableSubmit($submitButton); $.ajax({ type: 'POST', url: urlToPostTo, data: dataToPost, success: function(data) { if (CFS.redirectTo) { $submitButton.val(CFS.msgRedirect); if (CFS.nameField) { var nameFieldVal = ''; if ($("input[name='" + CFS.nameField + "']", $form)) { nameFieldVal = $("input[name='" + CFS.nameField + "']", $form).val(); } if (nameFieldVal) { CFS.setCookie('name', nameFieldVal, 60); } } window.location.replace(CFS.redirectTo); } else { CFS.enableSubmit($submitButton); } }, error: function() { console.log('Campaigner.com error!'); CFS.enableSubmit($submitButton); } }); } CFS.disableSubmit = function($button) { $button.attr("disabled", "disabled"); $button.val(CFS.msgPleaseWait); } CFS.enableSubmit = function($button) { $button.val(CFS.submitButtonText); $button.removeAttr("disabled"); } CFS.setCookie = function(name, value, seconds) { var d = new Date(); d.setTime(d.getTime() + (seconds * 1000)); var expires = 'expires=' + d.toUTCString(); document.cookie = name + '=' + value + ';' + expires + ';path=/'; } CFS.getCookie = function(name) { name += '='; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ''; } CFS.setNameFromSubmit = function() { if (CFS.nameFromSubmitField) { var elem = document.getElementById(CFS.nameFromSubmitField); var savedName = CFS.getCookie('name'); if (elem && savedName) { elem.innerHTML = savedName; } } } })(); ------Name Field Captured----- <p>Hello my name is <span id="nameFromSubmit">NAME HERE</span> <script src="custom-submit.js" type="text/javascript"></script> <script type="text/javascript"> if ((typeof CFS !== 'undefined') && CFS.setNameFromSubmit) { CFS.nameFromSubmitField = 'nameFromSubmit'; CFS.setNameFromSubmit(); } </script>
Inserting cookie value into hidden fields
I'm having trouble getting two cookie values and adding them to a form field on my website. Below is the script I've added, which also populates the values in JavsScript Console; however I can't get the cookie values into the form fields. Form fields: <input type="text" id="usource" name="usource" value=""> <input type="text" id="referrer" name="referrer" value=""> I've tried this JS to populate the "usource" and "referrer" field, but it doesn't seem to work. Am I missing something? document.getElementById("usource").value = utmCookie.utm_source; document.getElementById("referrer").value = utmCookie.referrer; This is the script I'm using which saves UTM parameters in cookies whenever there are any UTM parameters in the URL. It also saves the initial referrer information in a cookie which is ever (365 days) overwritten. var utmCookie = { cookieNamePrefix: "", utmParams: [ "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content" ], cookieExpiryDays: 365, // From http://www.quirksmode.org/js/cookies.html createCookie: function (name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = this.cookieNamePrefix + name + "=" + value + expires + "; domain=.mywebsite.com; path=/"; }, readCookie: function (name) { var nameEQ = this.cookieNamePrefix + name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; }, eraseCookie: function (name) { this.createCookie(name, "", -1); }, getParameterByName: function (name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); console.log(name); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.search); if (results == null) { return ""; } else { return decodeURIComponent(results[1].replace(/\+/g, " ")); } }, utmPresentInUrl: function () { var present = false; for (var i = 0; i < this.utmParams.length; i++) { var param = this.utmParams[i]; var value = this.getParameterByName(param); console.log(param + ' = ' + value); if (value != "" && value != undefined) { present = true; } } return present; }, writeUtmCookieFromParams: function () { for (var i = 0; i < this.utmParams.length; i++) { var param = this.utmParams[i]; var value = this.getParameterByName(param); this.writeCookieOnce(param, value) } }, writeCookieOnce: function (name, value) { var existingValue = this.readCookie(name); if (!existingValue) { this.createCookie(name, value, this.cookieExpiryDays); } }, writeReferrerOnce: function () { value = document.referrer; if (value === "" || value === undefined) { this.writeCookieOnce("referrer", "direct"); } else { this.writeCookieOnce("referrer", value); } }, referrer: function () { return this.readCookie("referrer"); } }; utmCookie.writeReferrerOnce(); if (utmCookie.utmPresentInUrl()) { utmCookie.writeUtmCookieFromParams(); }
ASP.NET referencing a javascript function
I have an ASP.NET page, written in VB.NET, that I'm trying to use javascript on. The script takes the value from one listbox and inserts it into another list box. I'm using a master page, which I'm pretty sure is the issue. Here's the javascript: function OT_transferLeft() { moveSelectedOptions(this.right, this.left, this.autoSort, this.staticOptionRegex); this.update(); } function OT_transferRight() { moveSelectedOptions(this.left, this.right, this.autoSort, this.staticOptionRegex); this.update(); } function OT_transferAllLeft() { moveAllOptions(this.right, this.left, this.autoSort, this.staticOptionRegex); this.update(); } function OT_transferAllRight() { moveAllOptions(this.left, this.right, this.autoSort, this.staticOptionRegex); this.update(); } function OT_saveRemovedLeftOptions(f) { this.removedLeftField = f; } function OT_saveRemovedRightOptions(f) { this.removedRightField = f; } function OT_saveAddedLeftOptions(f) { this.addedLeftField = f; } function OT_saveAddedRightOptions(f) { this.addedRightField = f; } function OT_saveNewLeftOptions(f) { this.newLeftField = f; } function OT_saveNewRightOptions(f) { this.newRightField = f; } function OT_update() { var removedLeft = new Object(); var removedRight = new Object(); var addedLeft = new Object(); var addedRight = new Object(); var newLeft = new Object(); var newRight = new Object(); for (var i = 0; i < this.left.options.length; i++) { var o = this.left.options[i]; newLeft[o.value] = 1; if (typeof (this.originalLeftValues[o.value]) == "undefined") { addedLeft[o.value] = 1; removedRight[o.value] = 1; } } for (var i = 0; i < this.right.options.length; i++) { var o = this.right.options[i]; newRight[o.value] = 1; if (typeof (this.originalRightValues[o.value]) == "undefined") { addedRight[o.value] = 1; removedLeft[o.value] = 1; } } if (this.removedLeftField != null) { this.removedLeftField.value = OT_join(removedLeft, this.delimiter); } if (this.removedRightField != null) { this.removedRightField.value = OT_join(removedRight, this.delimiter); } if (this.addedLeftField != null) { this.addedLeftField.value = OT_join(addedLeft, this.delimiter); } if (this.addedRightField != null) { this.addedRightField.value = OT_join(addedRight, this.delimiter); } if (this.newLeftField != null) { this.newLeftField.value = OT_join(newLeft, this.delimiter); } if (this.newRightField != null) { this.newRightField.value = OT_join(newRight, this.delimiter); } } function OT_join(o, delimiter) { var val; var str = ""; for (val in o) { if (str.length > 0) { str = str + delimiter; } str = str + val; } return str; } function OT_setDelimiter(val) { this.delimiter = val; } function OT_setAutoSort(val) { this.autoSort = val; } function OT_setStaticOptionRegex(val) { this.staticOptionRegex = val; } function OT_init(theform) { this.form = theform; if (!theform[this.left]) { alert("OptionTransfer init(): Left select list does not exist in form!"); return false; } if (!theform[this.right]) { alert("OptionTransfer init(): Right select list does not exist in form!"); return false; } this.left = theform[this.left]; this.right = theform[this.right]; for (var i = 0; i < this.left.options.length; i++) { this.originalLeftValues[this.left.options[i].value] = 1; } for (var i = 0; i < this.right.options.length; i++) { this.originalRightValues[this.right.options[i].value] = 1; } if (this.removedLeftField != null) { this.removedLeftField = theform[this.removedLeftField]; } if (this.removedRightField != null) { this.removedRightField = theform[this.removedRightField]; } if (this.addedLeftField != null) { this.addedLeftField = theform[this.addedLeftField]; } if (this.addedRightField != null) { this.addedRightField = theform[this.addedRightField]; } if (this.newLeftField != null) { this.newLeftField = theform[this.newLeftField]; } if (this.newRightField != null) { this.newRightField = theform[this.newRightField]; } this.update(); } // ------------------------------------------------------------------- // OptionTransfer() // This is the object interface. // ------------------------------------------------------------------- function OptionTransfer(l, r) { this.form = null; this.left = l; this.right = r; this.autoSort = true; this.delimiter = ","; this.staticOptionRegex = ""; this.originalLeftValues = new Object(); this.originalRightValues = new Object(); this.removedLeftField = null; this.removedRightField = null; this.addedLeftField = null; this.addedRightField = null; this.newLeftField = null; this.newRightField = null; this.transferLeft = OT_transferLeft; this.transferRight = OT_transferRight; this.transferAllLeft = OT_transferAllLeft; this.transferAllRight = OT_transferAllRight; this.saveRemovedLeftOptions = OT_saveRemovedLeftOptions; this.saveRemovedRightOptions = OT_saveRemovedRightOptions; this.saveAddedLeftOptions = OT_saveAddedLeftOptions; this.saveAddedRightOptions = OT_saveAddedRightOptions; this.saveNewLeftOptions = OT_saveNewLeftOptions; this.saveNewRightOptions = OT_saveNewRightOptions; this.setDelimiter = OT_setDelimiter; this.setAutoSort = OT_setAutoSort; this.setStaticOptionRegex = OT_setStaticOptionRegex; this.init = OT_init; this.update = OT_update; } var lb1 = document.getElementById("<%=lbSiteType.ClientID%>"); var lb2 = document.getElementById("<%=lbSelectedSiteType.ClientID%>"); var opt = new OptionTransfer(lb1, lb2); alert(opt); opt.setAutoSort(true); opt.setDelimiter(","); opt.setStaticOptionRegex("^(Bill|Bob|Matt)$"); opt.saveRemovedLeftOptions("removedLeft"); opt.saveRemovedRightOptions("removedRight"); opt.saveAddedLeftOptions("addedLeft"); opt.saveAddedRightOptions("addedRight"); opt.saveNewLeftOptions("newLeft"); opt.saveNewRightOptions("newRight"); and here's the code from the control: <asp:Button ID="btnMoveAll" Text=" >> " CssClass="button7" CausesValidation="false" ONCLICK="opt.transferRight()" runat="server" /><br /> In short, it doesn't work. I keep getting an 'opt' is not a member of the page. Can someone explain how I can properly call this code?
To invoke client Methods(javascript) use OnClientClick <asp:Button ID="btnMoveAll" Text="" CssClass="button7" CausesValidation="false" OnClientClick="opt.transferRight()" runat="server" />
Browser Compatibility (Javascript)
I'm rewriting the scripts for a site in regular Javascript to speed up the color picker, however if you view it in Firefox and IE, it doesn't work (But it works fine in Chrome). I was just really hoping to get some help with this: https://www.sinister.ly/index.php <div id="theme_styler"> <div class="option default" id="red"></div> <div class="option" id="green"></div> <div class="option" id="blue"></div> </div> The specific code that seems to be the problem: var optionalStylesheet = document.getElementsByClassName("stylesheet_optional"); var blueStylesheet = document.getElementById("stylesheet_blue"); var greenStylesheet = document.getElementById("stylesheet_green"); var storedThemeColor = readCookie('themeColor'); var currentFiconPath; function changeColor(path) { var all = document.getElementsByClassName("ficon"); for (var i=0, max=all.length; i < max; i++) { all[i].src = all[i].src.replace(/ficons\/((green|blue)\/)?/, 'ficons/' + path + '/'); } } This is in the header: // AD JS document.getElementsByClassName = function(cl) { var retnode = []; var elem = this.getElementsByTagName('*'); for (var i = 0; i < elem.length; i++) { if((' ' + elem[i].className + ' ').indexOf(' ' + cl + ' ') > -1) retnode.push(elem[i]); } return retnode; }; function readCookie(name) { var ca = document.cookie.split(';'); var nameEQ = name + "="; for(var i=0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; } function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname + "=" + cvalue + "; " + expires; } var optionalStylesheet = document.getElementsByClassName("stylesheet_optional"); var blueStylesheet = document.getElementById("stylesheet_blue"); var greenStylesheet = document.getElementById("stylesheet_green"); var storedThemeColor = readCookie('themeColor'); var currentFiconPath; function changeColor(path) { var all = document.getElementsByClassName("ficon"); for (var i=0, max=all.length; i < max; i++) { all[i].src = all[i].src.replace(/ficons\/((green|blue)\/)?/, 'ficons/' + path + '/'); } } var gs = document.createElement("link"); gs.type = "text/css"; gs.className = "stylesheet_optional"; gs.id = "stylesheet_blue"; gs.rel = "stylesheet"; gs.title = "mystyle"; gs.href = "images/sinisterly/color_blue.css"; var bs = document.createElement("link"); bs.type = "text/css"; bs.className = "stylesheet_optional"; bs.id = "stylesheet_green"; bs.rel = "stylesheet"; bs.title = "mystyle"; bs.href = "images/sinisterly/color_green.css"; var head = document.getElementsByTagName("head")[0]; var links = head.getElementsByTagName("link"); for(var x=0; x<links.length; x++) { var href = links[x].href; if(href.indexOf('/color_green.css') >0 || href.indexOf('/color_blue.css') >0){ head.removeChild(links[x]); } } if (storedThemeColor == "green"){ head.appendChild(bs); } else if (storedThemeColor == "blue") { head.appendChild(gs); } // End AD JS And this in the footer if (storedThemeColor == null) { setCookie('themeColor', 'default', 7); currentFiconPath = ''; return currentFiconPath; } else if (storedThemeColor != null) { if (storedThemeColor == 'default') { currentFiconPath = ''; optionalStylesheet.disabled = true; return currentFiconPath; } else if (storedThemeColor == 'blue') { currentFiconPath = "blue"; changeColor(currentFiconPath); optionalStylesheet.disabled = true; blueStylesheet.disabled = false; return currentFiconPath; } else if (storedThemeColor == 'green') { currentFiconPath = "green"; changeColor(currentFiconPath); optionalStylesheet.disabled = true; greenStylesheet.disabled = false; return currentFiconPath; } }
Change: var blueStylesheet = document.getElementById("#stylesheet_blue"); var greenStylesheet = document.getElementById("#stylesheet_green"); to: var blueStylesheet = document.getElementById("stylesheet_blue"); var greenStylesheet = document.getElementById("stylesheet_green"); There's no # at the beginning of the stylesheet IDs. I don't know why it's working in Chrome -- when I try it I get undefined in Chrome.
Firefox Addon Development : Detecting non-compatible addons?
Few addons are not compatible with mine, so how to detect their presence and inform the user. Thanks
OK got it here is how this is done : function isExtEnabled(){ if(!Application.extensions.has('EXTENSION_ID_HERE')) { return false; } return true; }
Here is an example from the evil noscript-1.9.2.xpi which modified adblock plugin settings function MRD(ns) { this.enabled = ns.getPref("mrd", true); if (!this.enabled) return; var c = CC[this.id]; if (c) { this.ns = ns; this.c = c.createInstance().wrappedJSObject; this._w._mrd = this; var eh = this.c["elemhide"]; eh.watch("url", this._w); eh.apply(); ns.mrd = this; ns.initContentPolicy(); } else this.enabled = false; } MRD.prototype = { id: "#mozilla.org/adblockplus;1", _nobind: "{-moz-binding: none !important}", _ms: null, _w: function(p, o, n) { if (!n) return n; var mrd = arguments.callee._mrd; var u = decodeURIComponent(n.spec); var mm = u.match(/#-moz-document\s+domain[^\)]*?(?:(?:noscript|flashgot|hackademix)\.net|informaction\.com|googlesyndication\.com)[^\}]*\}/g); if (mm) { var ns = mrd.ns; mrd._ms = mm.join('').replace(/(\{[^\{\}]*)\{[^\}]*/g, '$1' + mrd._nobind); } /* var uu = n.spec.split(','); uu[1] = encodeURIComponent(decodeURIComponent(uu[1]).replace(/#-moz-document\s+domain[^\)]*?(?:(?:noscript|flashgot|hackademix)\.net|informaction\.com|googlesyndication\.com)[^\}]*\}/g, '')); n.spec = uu.join(','); */ mrd.ns.delayExec(function() { mrd.apply(); }, 0); return n; }, _dd: function(a, s) { return "#-moz-document domain(" + a.join("),domain(") + "){" + s + "} "; }, get _def() { delete this.__proto__._def; return this.__proto__._def = this.ns.prefService.getDefaultBranch(this.ns.prefs.root).getCharPref("default"); }, get _wl() { delete this.__proto__._wl; return this.__proto__._wl = this._def.match(/\w+[^r].\.n\w+|in\w+on\.c\w+/g).concat(this.ns.getPref("xblHack", "").split(/\s+/)); }, get _wlrx() { delete this.__proto__._wlrx; return this.__proto__._wlrx = new RegExp("^(?:[\\w\\-\\.]*\\.)?(?:" + this._wl.join("|").replace(/\./g, "\\.").concat(")$")); }, get _es() { delete this.__proto__._es; try { var ss = [], lastS = ''; for(var j = 0; j < 5; j++) { ss.push(lastS += " #k" + j); } es = this._dd(this._wl, ss.join(' *,') + ' *' + this._nobind) + this._dd(this._def.match(/\w+[^r].\.n\w+|\w+on\.c\w+/g), "#a\u0064s, #\u0061ds .ad" + this._nobind); } catch (e) { if (this.ns.consoleDump) this.ns.dump("MRD ES Error: " + e); } return this.__proto__._es = es; }, apply: function() { var ns = this.ns; for each(var s in [this._es, this._ms]){ if (s) { ns.updateStyleSheet(s, false); ns.updateStyleSheet(s, true); } } }, attach: function() { if (!this.enabled) return false; try { var p = this.c.policy; var ns = this.ns; var wlrx = this._wlrx; if (!wlrx) return false; ns._mrd_shouldLoad = ns.shouldLoad; ns.shouldLoad = function(ct, cl, ro, ctx, mm, internal) { if (!internal) try { var w = ctx && (ctx.defaultView || ctx.ownerDocument && ctx.ownerDocument.defaultView || ctx); if (w) { l = w.top.location; if (!(/^https?/.test(l.protocol) && wlrx.test(l.hostname))) { var res = p.shouldLoad(ct, cl, ro, ctx, mm, internal); if (res != CP_OK) return res; } } } catch(e) { if (ns.consoleDump) ns.dump(e); } return ns._mrd_shouldLoad(ct, cl, ro, ctx, mm, internal); }; } catch(e) { if (this.ns.consoleDump) this.ns.dump("MRD Attach Error: " + e); return false; } return true; } }