Google Reviews Not Being Fetched - javascript

My google reviews are not being fetched. I've tried the code below but it doesn't work. I've created an api and put this in along with my placeid in all of the code below but nothing displays.
I followed multiple tutorials which all give basically the same code. I'm not sure why this isn't working.
Does anyone know what I'm doing wrong or have any suggestions on how to implement this in an easier way?
html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/js/google-places.js "></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&key=[API_KEY]"></script>
<script>
jQuery(document).ready(function() {
$("#google-reviews").googlePlaces({
placeId: '[PLACES_ID]',
render: ['reviews'],
min_rating: 3,
max_rows: 0
});
});
</script>
</head>
<body>
<div id="google-reviews"></div>
</body>
javascript:
/* https://github.com/peledies/google-places */
(function($) {
var namespace = 'googlePlaces';
$.googlePlaces = function(element, options) {
var defaults = {
placeId: 'PLACEID' // placeId provided by google api documentation
, render: ['reviews']
, min_rating: 3
, max_rows: 0
, map_plug_id: 'map-plug'
, rotateTime: false
, shorten_names: true
, schema:{
displayElement: '#schema'
, type: 'Store'
, beforeText: 'Google Users Have Rated'
, middleText: 'based on'
, afterText: 'ratings and reviews'
, image: null
, priceRange: null
}
, address:{
displayElement: "#google-address"
}
, phone:{
displayElement: "#google-phone"
}
, staticMap:{
displayElement: "#google-static-map"
, width: 512
, height: 512
, zoom: 17
, type: "roadmap"
}
, hours:{
displayElement: "#google-hours"
}
};
var plugin = this;
plugin.settings = {}
var $element = $(element),
element = element;
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
plugin.settings.schema = $.extend({}, defaults.schema, options.schema);
$element.html("<div id='" + plugin.settings.map_plug_id + "'></div>"); // create a plug for google to load data into
initialize_place(function(place){
plugin.place_data = place;
// Trigger event before render
$element.trigger('beforeRender.' + namespace);
if(plugin.settings.render.indexOf('rating') > -1){
renderRating(plugin.place_data.rating);
}
// render specified sections
if(plugin.settings.render.indexOf('reviews') > -1){
renderReviews(plugin.place_data.reviews);
if(!!plugin.settings.rotateTime) {
initRotation();
}
}
if(plugin.settings.render.indexOf('address') > -1){
renderAddress(
capture_element(plugin.settings.address.displayElement)
, plugin.place_data.adr_address
);
}
if(plugin.settings.render.indexOf('phone') > -1){
renderPhone(
capture_element(plugin.settings.phone.displayElement)
, plugin.place_data.formatted_phone_number
);
}
if(plugin.settings.render.indexOf('staticMap') > -1){
renderStaticMap(
capture_element(plugin.settings.staticMap.displayElement)
, plugin.place_data.formatted_address
);
}
if(plugin.settings.render.indexOf('hours') > -1){
renderHours(
capture_element(plugin.settings.hours.displayElement)
, plugin.place_data.opening_hours
);
}
// render schema markup
addSchemaMarkup(
capture_element(plugin.settings.schema.displayElement)
, plugin.place_data
);
// Trigger event after render
$element.trigger('afterRender.' + namespace);
});
}
var capture_element = function(element){
if(element instanceof jQuery){
return element;
}else if(typeof element == 'string'){
try{
var ele = $(element);
if( ele.length ){
return ele;
}else{
throw 'Element [' + element + '] couldnt be found in the DOM. Skipping '+element+' markup generation.';
}
}catch(e){
console.warn(e);
}
}
}
var initialize_place = function(c){
var map = new google.maps.Map(document.getElementById(plugin.settings.map_plug_id));
var request = {
placeId: plugin.settings.placeId
};
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
c(place);
}
});
}
var sort_by_date = function(ray) {
ray.sort(function(a, b){
var keyA = new Date(a.time),
keyB = new Date(b.time);
// Compare the 2 dates
if(keyA < keyB) return -1;
if(keyA > keyB) return 1;
return 0;
});
return ray;
}
var filter_minimum_rating = function(reviews){
for (var i = reviews.length -1; i >= 0; i--) {
if(reviews[i].rating < plugin.settings.min_rating){
reviews.splice(i,1);
}
}
return reviews;
}
var renderRating = function(rating){
var html = "";
var star = renderAverageStars(rating);
html = "<div class='average-rating'><h4>"+star+"</h4></div>";
$element.append(html);
}
var shorten_name = function(name) {
if (name.split(" ").length > 1) {
var xname = "";
xname = name.split(" ");
return xname[0] + " " + xname[1][0] + ".";
}
}
var renderReviews = function(reviews){
reviews = sort_by_date(reviews);
reviews = filter_minimum_rating(reviews);
var html = "";
var row_count = (plugin.settings.max_rows > 0)? plugin.settings.max_rows - 1 : reviews.length - 1;
// make sure the row_count is not greater than available records
row_count = (row_count > reviews.length-1)? reviews.length -1 : row_count;
for (var i = row_count; i >= 0; i--) {
var stars = renderStars(reviews[i].rating);
var date = convertTime(reviews[i].time);
if(plugin.settings.shorten_names == true) {
var name = shorten_name(reviews[i].author_name);
} else {
var name = reviews[i].author_name + "</span><span class='review-sep'>, </span>";
};
html = html+"<div class='review-item'><div class='review-meta'><span class='review-author'>"+name+"<span class='review-date'>"+date+"</span></div>"+stars+"<p class='review-text'>"+reviews[i].text+"</p></div>"
};
$element.append(html);
}
var renderHours = function(element, data){
if(element instanceof jQuery){
var html = "<ul>";
data.weekday_text.forEach(function(day){
html += "<li>"+day+"</li>";
});
html += "</ul>";
element.append(html);
}
}
var renderStaticMap = function(element, data){
if(element instanceof jQuery){
var map = plugin.settings.staticMap;
element.append(
"<img src='https://maps.googleapis.com/maps/api/staticmap"+
"?size="+map.width+"x"+map.height+
"&zoom="+map.zoom+
"&maptype="+map.type+
"&markers=size:large%7Ccolor:red%7C"+data+"'>"+
"</img>");
}
}
var renderAddress = function(element, data){
if(element instanceof jQuery){
element.append(data);
}
}
var renderPhone = function(element, data){
if(element instanceof jQuery){
element.append(data);
}
}
var initRotation = function() {
var $reviewEls = $element.children('.review-item');
var currentIdx = $reviewEls.length > 0 ? 0 : false;
$reviewEls.hide();
if(currentIdx !== false) {
$($reviewEls[currentIdx]).show();
setInterval(function(){
if(++currentIdx >= $reviewEls.length) {
currentIdx = 0;
}
$reviewEls.hide();
$($reviewEls[currentIdx]).fadeIn('slow');
}, plugin.settings.rotateTime);
}
}
var renderStars = function(rating){
var stars = "<div class='review-stars'><ul>";
// fill in gold stars
for (var i = 0; i < rating; i++) {
stars = stars+"<li><i class='star'></i></li>";
};
// fill in empty stars
if(rating < 5){
for (var i = 0; i < (5 - rating); i++) {
stars = stars+"<li><i class='star inactive'></i></li>";
};
}
stars = stars+"</ul></div>";
return stars;
}
var renderAverageStars = function(rating){
var stars = "<div class='review-stars'><ul><li><i>"+rating+" </i></li>";
var activeStars = parseInt(rating);
var inactiveStars = 5 - activeStars;
var width = (rating - activeStars) * 100 + '%';
// fill in gold stars
for (var i = 0; i < activeStars; i++) {
stars += "<li><i class='star'></i></li>";
};
// fill in empty stars
if(inactiveStars > 0){
for (var i = 0; i < inactiveStars; i++) {
if (i === 0) {
stars += "<li style='position: relative;'><i class='star inactive'></i><i class='star' style='position: absolute;top: 0;left: 0;overflow: hidden;width: "+width+"'></i></li>";
} else {
stars += "<li><i class='star inactive'></i></li>";
}
};
}
stars += "</ul></div>";
return stars;
}
var convertTime = function(UNIX_timestamp){
var a = new Date(UNIX_timestamp * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var time = months[a.getMonth()] + ' ' + a.getDate() + ', ' + a.getFullYear();
return time;
}
var addSchemaMarkup = function(element, placeData) {
if(element instanceof jQuery){
var schema = plugin.settings.schema;
var schemaMarkup = '<span itemscope="" itemtype="http://schema.org/' + schema.type + '">';
if(schema.image !== null) {
schemaMarkup += generateSchemaItemMarkup('image', schema.image);
} else {
console.warn('Image is required for some schema types. Visit https://search.google.com/structured-data/testing-tool to test your schema output.');
}
if(schema.priceRange !== null) {
schemaMarkup += generateSchemaItemMarkup('priceRange', schema.priceRange);
}
schemaMarkup += generateSchemaItemMarkup('url', location.origin);
schemaMarkup += generateSchemaItemMarkup('telephone', plugin.place_data.formatted_phone_number );
schemaMarkup += generateSchemaAddressMarkup();
schemaMarkup += generateSchemaRatingMarkup(placeData, schema);
schemaMarkup += '</span>';
element.append(schemaMarkup);
}
}
var generateSchemaAddressMarkup = function() {
var $address = $('<div />', {
itemprop: "address"
, itemscope: ''
, itemtype: "http://schema.org/PostalAddress"
}).css('display', 'none');
$address.append(plugin.place_data.adr_address);
$address.children('.street-address').attr('itemprop', 'streetAddress');
$address.children('.locality').attr('itemprop', 'addressLocality');
$address.children('.region').attr('itemprop', 'addressRegion');
$address.children('.postal-code').attr('itemprop', 'postalCode');
$address.children('.country-name').attr('itemprop', 'addressCountry');
return $address[0].outerHTML;
}
var generateSchemaRatingMarkup = function(placeData, schema) {
var reviews = placeData.reviews;
var lastIndex = reviews.length - 1;
var reviewPointTotal = 0;
for (var i = lastIndex; i >= 0; i--) {
reviewPointTotal += reviews[i].rating;
};
var averageReview = reviewPointTotal / ( reviews.length );
return schema.beforeText + ' <span itemprop="name">' + placeData.name + '</span> '
+ '<span itemprop="aggregateRating" itemscope="" itemtype="http://schema.org/AggregateRating">'
+ '<span itemprop="ratingValue">' + averageReview.toFixed(2) + '</span>/<span itemprop="bestRating">5</span> '
+ schema.middleText + ' <span itemprop="ratingCount">' + reviews.length + '</span> '
+ schema.afterText
+ '</span>'
}
var generateSchemaItemMarkup = function(name, value) {
return '<meta itemprop="' + name + '" content="' + value + '">'
}
plugin.init();
}
$.fn.googlePlaces = function(options) {
return this.each(function() {
if (undefined == $(this).data(namespace)) {
var plugin = new $.googlePlaces(this, options);
$(this).data(namespace, plugin);
}
});
}
})(jQuery);
I've also tried just this instead of everything above but still nothing displays.
html:
<div id="google-reviews"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://tutorialswebsite.com/cdn/google_places.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=APIKEY&signed_in=true&libraries=places"></script>
<script>
jQuery(document).ready(function( $ ) {
$("#google-reviews").googlePlaces({
placeId: 'PLACEID' //Find placeID #: https://developers.google.com/places/place-id
, render: ['reviews']
, min_rating:3
, max_rows:5
,rotateTime: false
, shorten_names: true
});
});
</script>
Edit: When I checked the console I received the following errors:
Failed to load resource: the server responded with a status of 404 ()
jquery.min.js:2 jQuery.Deferred exception: $(...).googlePlaces is not a function TypeError: $(...).googlePlaces is not a function
at HTMLDocument.<anonymous> (https://orlhometech.netlify.app/reviews.html?:208:26)
at j (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:29948)
at k (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:30262) undefined
r.Deferred.exceptionHook # jquery.min.js:2
jquery.min.js:2 Uncaught TypeError: $(...).googlePlaces is not a function
at HTMLDocument.<anonymous> (reviews.html:208)
at j (jquery.min.js:2)
at k (jquery.min.js:2)
util.js:235 Google Maps JavaScript API warning: SignedInNotSupported https://developers.google.com/maps/documentation/javascript/error-messages#signed-in-not-supported
Bv.j # util.js:235
(anonymous) # js?v=3.exp&key=AIzaSyBjy1orhutANXF-hI3r4LqJI2XeThpI1Dc&signed_in=true&libraries=places:168
Promise.then (async)
(anonymous) # js?v=3.exp&key=AIzaSyBjy1orhutANXF-hI3r4LqJI2XeThpI1Dc&signed_in=true&libraries=places:168
js?v=3.exp&key=AIzaSyBjy1orhutANXF-hI3r4LqJI2XeThpI1Dc&signed_in=true&libraries=places:83 Google Maps JavaScript API error: ApiNotActivatedMapError
https://developers.google.com/maps/documentation/javascript/error-messages#api-not-activated-map-error
I don't know what all of that means but I'm pretty sure I created the api key correctly in the google console. Note this is for the second batch of code from my original post above, not the first batch.

Related

Reviews Not Being Fetched

My google reviews are not being fetched. I've tried the code below but it doesn't work. I've created an api and put this in along with my placeid in all of the code below but nothing displays.
I followed multiple tutorials which all give basically the same code. I'm not sure why this isn't working.
Does anyone know what I'm doing wrong or have any suggestions on how to implement this in an easier way.
html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/js/google-places.js "></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&key=[API_KEY]"></script>
<script>
jQuery(document).ready(function() {
$("#google-reviews").googlePlaces({
placeId: '[PLACES_ID]',
render: ['reviews'],
min_rating: 3,
max_rows: 0
});
});
</script>
</head>
<body>
<div id="google-reviews"></div>
</body>
javascript:
/* https://github.com/peledies/google-places */
(function($) {
var namespace = 'googlePlaces';
$.googlePlaces = function(element, options) {
var defaults = {
placeId: 'PLACEID' // placeId provided by google api documentation
, render: ['reviews']
, min_rating: 3
, max_rows: 0
, map_plug_id: 'map-plug'
, rotateTime: false
, shorten_names: true
, schema:{
displayElement: '#schema'
, type: 'Store'
, beforeText: 'Google Users Have Rated'
, middleText: 'based on'
, afterText: 'ratings and reviews'
, image: null
, priceRange: null
}
, address:{
displayElement: "#google-address"
}
, phone:{
displayElement: "#google-phone"
}
, staticMap:{
displayElement: "#google-static-map"
, width: 512
, height: 512
, zoom: 17
, type: "roadmap"
}
, hours:{
displayElement: "#google-hours"
}
};
var plugin = this;
plugin.settings = {}
var $element = $(element),
element = element;
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
plugin.settings.schema = $.extend({}, defaults.schema, options.schema);
$element.html("<div id='" + plugin.settings.map_plug_id + "'></div>"); // create a plug for google to load data into
initialize_place(function(place){
plugin.place_data = place;
// Trigger event before render
$element.trigger('beforeRender.' + namespace);
if(plugin.settings.render.indexOf('rating') > -1){
renderRating(plugin.place_data.rating);
}
// render specified sections
if(plugin.settings.render.indexOf('reviews') > -1){
renderReviews(plugin.place_data.reviews);
if(!!plugin.settings.rotateTime) {
initRotation();
}
}
if(plugin.settings.render.indexOf('address') > -1){
renderAddress(
capture_element(plugin.settings.address.displayElement)
, plugin.place_data.adr_address
);
}
if(plugin.settings.render.indexOf('phone') > -1){
renderPhone(
capture_element(plugin.settings.phone.displayElement)
, plugin.place_data.formatted_phone_number
);
}
if(plugin.settings.render.indexOf('staticMap') > -1){
renderStaticMap(
capture_element(plugin.settings.staticMap.displayElement)
, plugin.place_data.formatted_address
);
}
if(plugin.settings.render.indexOf('hours') > -1){
renderHours(
capture_element(plugin.settings.hours.displayElement)
, plugin.place_data.opening_hours
);
}
// render schema markup
addSchemaMarkup(
capture_element(plugin.settings.schema.displayElement)
, plugin.place_data
);
// Trigger event after render
$element.trigger('afterRender.' + namespace);
});
}
var capture_element = function(element){
if(element instanceof jQuery){
return element;
}else if(typeof element == 'string'){
try{
var ele = $(element);
if( ele.length ){
return ele;
}else{
throw 'Element [' + element + '] couldnt be found in the DOM. Skipping '+element+' markup generation.';
}
}catch(e){
console.warn(e);
}
}
}
var initialize_place = function(c){
var map = new google.maps.Map(document.getElementById(plugin.settings.map_plug_id));
var request = {
placeId: plugin.settings.placeId
};
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
c(place);
}
});
}
var sort_by_date = function(ray) {
ray.sort(function(a, b){
var keyA = new Date(a.time),
keyB = new Date(b.time);
// Compare the 2 dates
if(keyA < keyB) return -1;
if(keyA > keyB) return 1;
return 0;
});
return ray;
}
var filter_minimum_rating = function(reviews){
for (var i = reviews.length -1; i >= 0; i--) {
if(reviews[i].rating < plugin.settings.min_rating){
reviews.splice(i,1);
}
}
return reviews;
}
var renderRating = function(rating){
var html = "";
var star = renderAverageStars(rating);
html = "<div class='average-rating'><h4>"+star+"</h4></div>";
$element.append(html);
}
var shorten_name = function(name) {
if (name.split(" ").length > 1) {
var xname = "";
xname = name.split(" ");
return xname[0] + " " + xname[1][0] + ".";
}
}
var renderReviews = function(reviews){
reviews = sort_by_date(reviews);
reviews = filter_minimum_rating(reviews);
var html = "";
var row_count = (plugin.settings.max_rows > 0)? plugin.settings.max_rows - 1 : reviews.length - 1;
// make sure the row_count is not greater than available records
row_count = (row_count > reviews.length-1)? reviews.length -1 : row_count;
for (var i = row_count; i >= 0; i--) {
var stars = renderStars(reviews[i].rating);
var date = convertTime(reviews[i].time);
if(plugin.settings.shorten_names == true) {
var name = shorten_name(reviews[i].author_name);
} else {
var name = reviews[i].author_name + "</span><span class='review-sep'>, </span>";
};
html = html+"<div class='review-item'><div class='review-meta'><span class='review-author'>"+name+"<span class='review-date'>"+date+"</span></div>"+stars+"<p class='review-text'>"+reviews[i].text+"</p></div>"
};
$element.append(html);
}
var renderHours = function(element, data){
if(element instanceof jQuery){
var html = "<ul>";
data.weekday_text.forEach(function(day){
html += "<li>"+day+"</li>";
});
html += "</ul>";
element.append(html);
}
}
var renderStaticMap = function(element, data){
if(element instanceof jQuery){
var map = plugin.settings.staticMap;
element.append(
"<img src='https://maps.googleapis.com/maps/api/staticmap"+
"?size="+map.width+"x"+map.height+
"&zoom="+map.zoom+
"&maptype="+map.type+
"&markers=size:large%7Ccolor:red%7C"+data+"'>"+
"</img>");
}
}
var renderAddress = function(element, data){
if(element instanceof jQuery){
element.append(data);
}
}
var renderPhone = function(element, data){
if(element instanceof jQuery){
element.append(data);
}
}
var initRotation = function() {
var $reviewEls = $element.children('.review-item');
var currentIdx = $reviewEls.length > 0 ? 0 : false;
$reviewEls.hide();
if(currentIdx !== false) {
$($reviewEls[currentIdx]).show();
setInterval(function(){
if(++currentIdx >= $reviewEls.length) {
currentIdx = 0;
}
$reviewEls.hide();
$($reviewEls[currentIdx]).fadeIn('slow');
}, plugin.settings.rotateTime);
}
}
var renderStars = function(rating){
var stars = "<div class='review-stars'><ul>";
// fill in gold stars
for (var i = 0; i < rating; i++) {
stars = stars+"<li><i class='star'></i></li>";
};
// fill in empty stars
if(rating < 5){
for (var i = 0; i < (5 - rating); i++) {
stars = stars+"<li><i class='star inactive'></i></li>";
};
}
stars = stars+"</ul></div>";
return stars;
}
var renderAverageStars = function(rating){
var stars = "<div class='review-stars'><ul><li><i>"+rating+" </i></li>";
var activeStars = parseInt(rating);
var inactiveStars = 5 - activeStars;
var width = (rating - activeStars) * 100 + '%';
// fill in gold stars
for (var i = 0; i < activeStars; i++) {
stars += "<li><i class='star'></i></li>";
};
// fill in empty stars
if(inactiveStars > 0){
for (var i = 0; i < inactiveStars; i++) {
if (i === 0) {
stars += "<li style='position: relative;'><i class='star inactive'></i><i class='star' style='position: absolute;top: 0;left: 0;overflow: hidden;width: "+width+"'></i></li>";
} else {
stars += "<li><i class='star inactive'></i></li>";
}
};
}
stars += "</ul></div>";
return stars;
}
var convertTime = function(UNIX_timestamp){
var a = new Date(UNIX_timestamp * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var time = months[a.getMonth()] + ' ' + a.getDate() + ', ' + a.getFullYear();
return time;
}
var addSchemaMarkup = function(element, placeData) {
if(element instanceof jQuery){
var schema = plugin.settings.schema;
var schemaMarkup = '<span itemscope="" itemtype="http://schema.org/' + schema.type + '">';
if(schema.image !== null) {
schemaMarkup += generateSchemaItemMarkup('image', schema.image);
} else {
console.warn('Image is required for some schema types. Visit https://search.google.com/structured-data/testing-tool to test your schema output.');
}
if(schema.priceRange !== null) {
schemaMarkup += generateSchemaItemMarkup('priceRange', schema.priceRange);
}
schemaMarkup += generateSchemaItemMarkup('url', location.origin);
schemaMarkup += generateSchemaItemMarkup('telephone', plugin.place_data.formatted_phone_number );
schemaMarkup += generateSchemaAddressMarkup();
schemaMarkup += generateSchemaRatingMarkup(placeData, schema);
schemaMarkup += '</span>';
element.append(schemaMarkup);
}
}
var generateSchemaAddressMarkup = function() {
var $address = $('<div />', {
itemprop: "address"
, itemscope: ''
, itemtype: "http://schema.org/PostalAddress"
}).css('display', 'none');
$address.append(plugin.place_data.adr_address);
$address.children('.street-address').attr('itemprop', 'streetAddress');
$address.children('.locality').attr('itemprop', 'addressLocality');
$address.children('.region').attr('itemprop', 'addressRegion');
$address.children('.postal-code').attr('itemprop', 'postalCode');
$address.children('.country-name').attr('itemprop', 'addressCountry');
return $address[0].outerHTML;
}
var generateSchemaRatingMarkup = function(placeData, schema) {
var reviews = placeData.reviews;
var lastIndex = reviews.length - 1;
var reviewPointTotal = 0;
for (var i = lastIndex; i >= 0; i--) {
reviewPointTotal += reviews[i].rating;
};
var averageReview = reviewPointTotal / ( reviews.length );
return schema.beforeText + ' <span itemprop="name">' + placeData.name + '</span> '
+ '<span itemprop="aggregateRating" itemscope="" itemtype="http://schema.org/AggregateRating">'
+ '<span itemprop="ratingValue">' + averageReview.toFixed(2) + '</span>/<span itemprop="bestRating">5</span> '
+ schema.middleText + ' <span itemprop="ratingCount">' + reviews.length + '</span> '
+ schema.afterText
+ '</span>'
}
var generateSchemaItemMarkup = function(name, value) {
return '<meta itemprop="' + name + '" content="' + value + '">'
}
plugin.init();
}
$.fn.googlePlaces = function(options) {
return this.each(function() {
if (undefined == $(this).data(namespace)) {
var plugin = new $.googlePlaces(this, options);
$(this).data(namespace, plugin);
}
});
}
})(jQuery);
I've also tried just this instead of everything above but still nothing displays.
html:
<div id="google-reviews"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://tutorialswebsite.com/cdn/google_places.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=APIKEY&signed_in=true&libraries=places"></script>
<script>
jQuery(document).ready(function( $ ) {
$("#google-reviews").googlePlaces({
placeId: 'PLACEID' //Find placeID #: https://developers.google.com/places/place-id
, render: ['reviews']
, min_rating:3
, max_rows:5
,rotateTime: false
, shorten_names: true
});
});
</script>

Blogger random post display to prevent no posts infinite loop

How can I get Blogger to display random posts, while preventing an infinite loop when there are no posts to display?
Here is my JavaScript code which I am attempting to use:
<script>
var dt_numposts = 10;
var dt_snippet_length = 100;
var dt_info = 'true';
var dt_comment = 'Comment';
var dt_disable = '';
var dt_current = [];
var dt_total_posts = 0;
var dt_current = new Array(dt_numposts);
function totalposts(json) {
dt_total_posts = json.feed.openSearch$totalResults.$t
}
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts\"><\/script>');
function getvalue() {
for (var i = 0; i < dt_numposts; i++) {
var found = false;
var rndValue = get_random();
for (var j = 0; j < dt_current.length; j++) {
if (dt_current[j] == rndValue) {
found = true;
break
}
};
if (found) {
i--
} else {
dt_current[i] = rndValue
}
}
};
function get_random() {
var ranNum = 1 + Math.round(Math.random() * (dt_total_posts - 1));
return ranNum
};
function random_list(json) {
a = location.href;
y = a.indexOf('?m=0');
for (var i = 0; i < dt_numposts; i++) {
var entry = json.feed.entry[i];
var dt_posttitle = entry.title.$t;
if ('content' in entry) {
var dt_get_snippet = entry.content.$t
} else {
if ('summary' in entry) {
var dt_get_snippet = entry.summary.$t
} else {
var dt_get_snippet = "";
}
};
dt_get_snippet = dt_get_snippet.replace(/<[^>]*>/g, "");
if (dt_get_snippet.length < dt_snippet_length) {
var dt_snippet = dt_get_snippet
} else {
dt_get_snippet = dt_get_snippet.substring(0, dt_snippet_length);
var space = dt_get_snippet.lastIndexOf(" ");
dt_snippet = dt_get_snippet.substring(0, space) + "…";
};
for (var j = 0; j < entry.link.length; j++) {
if ('thr$total' in entry) {
var dt_commentsNum = entry.thr$total.$t + ' ' + dt_comment
} else {
dt_commentsNum = dt_disable
};
if (entry.link[j].rel == 'alternate') {
var dt_posturl = entry.link[j].href;
if (y != -1) {
dt_posturl = dt_posturl + '?m=0'
}
var dt_postdate = entry.published.$t;
if ('media$thumbnail' in entry) {
var dt_thumb = entry.media$thumbnail.url
} else {
dt_thumb = "https://blogspot.com/"
}
}
};
document.write('<img alt="' + dt_posttitle + '" src="' + dt_thumb + '"/>');
document.write('<div>' + dt_posttitle + '</div>');
if (dt_info == 'true') {
document.write('<span>' + dt_postdate.substring(8, 10) + '/' + dt_postdate.substring(5, 7) + '/' + dt_postdate.substring(0, 4) + ' - ' + dt_commentsNum) + '</span>'
}
document.write('<div style="clear:both"></div>')
}
};
getvalue();
for (var i = 0; i < dt_numposts; i++) {
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?alt=json-in-script&start-index=' + dt_current[i] + '&max-results=1&callback=random_list\"><\/script>')
};
</script>
Expected output:
?
Actual output:
?
It looks like your post is mostly code; please add some more details.
It looks like you're trying to populate dt_current with dt_numposts = 10 elements. I modified getvalue() as follows, so that dt_numposts is capped at dt_total_posts, which may be 0. This allows the outer for loop to exit.
function getvalue() {
dt_numposts = (dt_total_posts < dt_numposts) ? dt_total_posts : dt_numposts;
// ...
I couldn't test this, because I don't have an example /feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts JSON resource, but it works for zero posts. Whether is works for dt_numposts > 0, you'll need to test!

element null in Magento

I upgrade magento from 1.8.1 to 1.9.0, and I have a problem with one js file:
TypeError: $(...) is null
$('product_addtocart_form').getElements().each(function(el) {
simple_product_pricing.js (line 1131, col 5)
I think this file is related to the Ayasoftware_SimpleProductPricing, maybe someone can help me to solve this. Before upgrade in 1.8.1 version everything was fine, in 1.9.0 version I have this error.
I will add here the entire js:
/*
Some of these override earlier varien/product.js methods, therefore
varien/product.js must have been included prior to this file.
some of these functions were initially written by Matt Dean ( http://organicinternet.co.uk/ )
*/
Product.Config.prototype.getMatchingSimpleProduct = function(){
var inScopeProductIds = this.getInScopeProductIds();
if ((typeof inScopeProductIds != 'undefined') && (inScopeProductIds.length == 1)) {
return inScopeProductIds[0];
}
return false;
};
/*
Find products which are within consideration based on user's selection of
config options so far
Returns a normal array containing product ids
allowedProducts is a normal numeric array containing product ids.
childProducts is a hash keyed on product id
optionalAllowedProducts lets you pass a set of products to restrict by,
in addition to just using the ones already selected by the user
*/
Product.Config.prototype.getInScopeProductIds = function(optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var allowedProducts = [];
if ((typeof optionalAllowedProducts != 'undefined') && (optionalAllowedProducts.length > 0)) {
allowedProducts = optionalAllowedProducts;
}
for(var s=0, len=this.settings.length-1; s<=len; s++) {
if (this.settings[s].selectedIndex <= 0){
break;
}
var selected = this.settings[s].options[this.settings[s].selectedIndex];
if (s==0 && allowedProducts.length == 0){
allowedProducts = selected.config.allowedProducts;
} else {
allowedProducts = allowedProducts.intersect(selected.config.allowedProducts).uniq();
}
}
//If we can't find any products (because nothing's been selected most likely)
//then just use all product ids.
if ((typeof allowedProducts == 'undefined') || (allowedProducts.length == 0)) {
productIds = Object.keys(childProducts);
} else {
productIds = allowedProducts;
}
return productIds;
};
Product.Config.prototype.getProductIdOfCheapestProductInScope = function(priceType, optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var productIds = this.getInScopeProductIds(optionalAllowedProducts);
var minPrice = Infinity;
var lowestPricedProdId = false;
//Get lowest price from product ids.
for (var x=0, len=productIds.length; x<len; ++x) {
var thisPrice = Number(childProducts[productIds[x]][priceType]);
if (thisPrice < minPrice) {
minPrice = thisPrice;
lowestPricedProdId = productIds[x];
}
}
return lowestPricedProdId;
};
Product.Config.prototype.getProductIdOfMostExpensiveProductInScope = function(priceType, optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var productIds = this.getInScopeProductIds(optionalAllowedProducts);
var maxPrice = 0;
var highestPricedProdId = false;
//Get highest price from product ids.
for (var x=0, len=productIds.length; x<len; ++x) {
var thisPrice = Number(childProducts[productIds[x]][priceType]);
if (thisPrice >= maxPrice) {
maxPrice = thisPrice;
highestPricedProdId = productIds[x];
}
}
return highestPricedProdId;
};
Product.OptionsPrice.prototype.updateSpecialPriceDisplay = function(price, finalPrice) {
var prodForm = $('product_addtocart_form');
jQuery('p.msg').hide();
jQuery('div.price-box').show();
var specialPriceBox = prodForm.select('p.special-price');
var oldPricePriceBox = prodForm.select('p.old-price, p.was-old-price');
var magentopriceLabel = prodForm.select('span.price-label');
if (price == finalPrice) {
//specialPriceBox.each(function(x) {x.hide();});
magentopriceLabel.each(function(x) {x.hide();});
oldPricePriceBox.each(function(x) { x.hide();
// x.removeClassName('old-price');
// x.addClassName('was-old-price');
});
jQuery('.product-shop').removeClass('sale-product') ;
}else{
specialPriceBox.each(function(x) {x.show();});
magentopriceLabel.each(function(x) {x.show();});
oldPricePriceBox.each(function(x) { x.show();
x.removeClassName('was-old-price');
x.addClassName('old-price');
});
jQuery('.product-shop').addClass('sale-product') ;
}
};
//This triggers reload of price and other elements that can change
//once all options are selected
Product.Config.prototype.reloadPrice = function() {
var childProductId = this.getMatchingSimpleProduct();
var childProducts = this.config.childProducts;
var usingZoomer = false;
if(this.config.imageZoomer){
usingZoomer = true;
}
if(childProductId){
var price = childProducts[childProductId]["price"];
var finalPrice = childProducts[childProductId]["finalPrice"];
optionsPrice.productPrice = finalPrice;
optionsPrice.productOldPrice = price;
optionsPrice.reload();
optionsPrice.reloadPriceLabels(true);
optionsPrice.updateSpecialPriceDisplay(price, finalPrice);
if(this.config.updateShortDescription) {
this.updateProductShortDescription(childProductId);
}
if(this.config.updateDescription) {
this.updateProductDescription(childProductId);
}
if(this.config.updateProductName) {
this.updateProductName(childProductId);
}
if(this.config.customStockDisplay) {
this.updateProductAvailability(childProductId);
}
this.showTierPricingBlock(childProductId, this.config.productId);
if (usingZoomer) {
this.showFullImageDiv(childProductId, this.config.productId);
} else {
if(this.config.updateproductimage) {
this.updateProductImage(childProductId);
}
}
} else {
var cheapestPid = this.getProductIdOfCheapestProductInScope("finalPrice");
var price = childProducts[cheapestPid]["price"];
var finalPrice = childProducts[cheapestPid]["finalPrice"];
optionsPrice.productPrice = finalPrice;
optionsPrice.productOldPrice = price;
optionsPrice.reload();
optionsPrice.reloadPriceLabels(false);
if(this.config.updateProductName) {
this.updateProductName(false);
}
if(this.config.updateShortDescription) {
this.updateProductShortDescription(false);
}
if(this.config.updateDescription) {
this.updateProductDescription(false);
}
if(this.config.customStockDisplay) {
this.updateProductAvailability(false);
}
optionsPrice.updateSpecialPriceDisplay(price, finalPrice);
this.showTierPricingBlock(false);
this.showCustomOptionsBlock(false, false);
if (usingZoomer) {
this.showFullImageDiv(false, false);
} else {
if(this.config.updateproductimage) {
this.updateProductImage(false);
}
}
}
};
Product.Config.prototype.updateProductImage = function(productId) {
var imageUrl = this.config.imageUrl;
if(productId && this.config.childProducts[productId].imageUrl) {
imageUrl = this.config.childProducts[productId].imageUrl;
}
if (!imageUrl) {
return;
}
if($('image')) {
$('image').src = imageUrl;
} else {
$$('#product_addtocart_form p.product-image img').each(function(el) {
var dims = el.getDimensions();
el.src = imageUrl;
el.width = dims.width;
el.height = dims.height;
});
}
};
Product.Config.prototype.updateProductName = function(productId) {
var productName = this.config.productName;
if (productId && this.config.ProductNames[productId].ProductName) {
productName = this.config.ProductNames[productId].ProductName;
}
$$('#product_addtocart_form div.product-name h1').each(function(el) {
el.innerHTML = productName;
});
var productSku = this.config.sku ;
if (productId && this.config.childProducts[productId].sku) {
productSku = this.config.childProducts[productId].sku ;
}
jQuery('.sku span').text(productSku) ;
var productDelivery = this.config.delivery;
if (productId && this.config.childProducts[productId].delivery) {
productDelivery = this.config.childProducts[productId].delivery ;
}
jQuery('.delivery-info').html(productDelivery) ;
var productReturns = this.config.returns;
if (productId && this.config.childProducts[productId].returns) {
productReturns = this.config.childProducts[productId].returns ;
}
jQuery('.returns-info').html(productReturns) ;
var productDownloads = this.config.downloads;
if (productId && this.config.childProducts[productId].downloads) {
productDownloads = this.config.childProducts[productId].downloads;
}
if (productDownloads) jQuery('.downloads-info').html(productDownloads) ;
else jQuery('.downloads-info').html('There are no downloads for this product') ;
var productAttribs = this.config.attributesTable;
if (productId && this.config.childProducts[productId].attributesTable) {
productAttribs = this.config.childProducts[productId].attributesTable ;
}
jQuery('.attribs-info').html(productAttribs) ;
decorateTable('product-attribute-specs-table') ;
if (productId && this.config.childProducts[productId].isNew) {
jQuery('.product-image .new-label').show() ;
} else {
jQuery('.product-image .new-label').hide() ;
}
if (productId && this.config.childProducts[productId].isOnSale) {
jQuery('.product-image .sale-label').show() ;
} else {
jQuery('.product-image .sale-label').hide() ;
}
if (productId) jQuery('input[name="pid"]').val(productId) ;
};
Product.Config.prototype.updateProductAvailability = function(productId) {
var stockInfo = this.config.stockInfo;
var is_in_stock = false;
var stockLabel = '';
if (productId && stockInfo[productId]["stockLabel"]) {
stockLabel = stockInfo[productId]["stockLabel"];
stockQty = stockInfo[productId]["stockQty"];
is_in_stock = stockInfo[productId]["is_in_stock"];
}
$$('#product_addtocart_form p.availability span').each(function(el) {
if(is_in_stock) {
$$('#product_addtocart_form p.availability').each(function(es) {
es.removeClassName('availability out-of-stock');
es.addClassName('availability in-stock');
});
el.innerHTML = /*stockQty + ' ' + */stockLabel;
} else {
$$('#product_addtocart_form p.availability').each(function(ef) {
ef.removeClassName('availability in-stock');
ef.addClassName('availability out-of-stock');
});
el.innerHTML = stockLabel;
}
});
};
Product.Config.prototype.updateProductShortDescription = function(productId) {
var shortDescription = this.config.shortDescription;
if (productId && this.config.shortDescriptions[productId].shortDescription) {
shortDescription = this.config.shortDescriptions[productId].shortDescription;
}
$$('#product_addtocart_form div.short-description div.std').each(function(el) {
el.innerHTML = shortDescription;
});
};
Product.Config.prototype.updateProductDescription = function(productId) {
var description = this.config.description;
if (productId && this.config.Descriptions[productId].Description) {
description = this.config.Descriptions[productId].Description;
}
$$('#product_tabs_description_tabbed_contents div.std').each(function(el) {
el.innerHTML = description;
});
};
Product.Config.prototype.updateProductAttributes = function(productId) {
var productAttributes = this.config.productAttributes;
if (productId && this.config.childProducts[productId].productAttributes) {
productAttributes = this.config.childProducts[productId].productAttributes;
}
//If config product doesn't already have an additional information section,
//it won't be shown for associated product either. It's too hard to work out
//where to place it given that different themes use very different html here
console.log(productAttributes) ;
$$('div.product-collateral div.attribs-info').each(function(el) {
el.innerHTML = productAttributes;
decorateTable('product-attribute-specs-table');
});
};
Product.Config.prototype.showCustomOptionsBlock = function(productId, parentId) {
var coUrl = this.config.ajaxBaseUrl + "co/?id=" + productId + '&pid=' + parentId;
var prodForm = $('product_addtocart_form');
if ($('SCPcustomOptionsDiv')==null) {
return;
}
Effect.Fade('SCPcustomOptionsDiv', { duration: 0.5, from: 1, to: 0.5 });
if(productId) {
//Uncomment the line below if you want an ajax loader to appear while any custom
//options are being loaded.
//$$('span.scp-please-wait').each(function(el) {el.show()});
//prodForm.getElements().each(function(el) {el.disable()});
new Ajax.Updater('SCPcustomOptionsDiv', coUrl, {
method: 'get',
evalScripts: true,
onComplete: function() {
$$('span.scp-please-wait').each(function(el) {el.hide()});
Effect.Fade('SCPcustomOptionsDiv', { duration: 0.5, from: 0.5, to: 1 });
//prodForm.getElements().each(function(el) {el.enable()});
}
});
} else {
$('SCPcustomOptionsDiv').innerHTML = '';
try{window.opConfig = new Product.Options([]);} catch(e){}
}
};
Product.OptionsPrice.prototype.reloadPriceLabels = function(productPriceIsKnown) {
var priceFromLabel = '';
var prodForm = $('product_addtocart_form');
if (!productPriceIsKnown && typeof spConfig != "undefined") {
priceFromLabel = spConfig.config.priceFromLabel;
}
var priceSpanId = 'configurable-price-from-' + this.productId;
var duplicatePriceSpanId = priceSpanId + this.duplicateIdSuffix;
if($(priceSpanId) && $(priceSpanId).select('span.configurable-price-from-label'))
$(priceSpanId).select('span.configurable-price-from-label').each(function(label) {
label.innerHTML = priceFromLabel;
});
if ($(duplicatePriceSpanId) && $(duplicatePriceSpanId).select('span.configurable-price-from-label')) {
$(duplicatePriceSpanId).select('span.configurable-price-from-label').each(function(label) {
label.innerHTML = priceFromLabel;
});
}
};
//SCP: Forces the 'next' element to have it's optionLabels reloaded too
Product.Config.prototype.configureElement = function(element) {
this.reloadOptionLabels(element);
if(element.value){
this.state[element.config.id] = element.value;
if(element.nextSetting){
element.nextSetting.disabled = false;
this.fillSelect(element.nextSetting);
this.reloadOptionLabels(element.nextSetting);
this.resetChildren(element.nextSetting);
}
}
else {
this.resetChildren(element);
}
this.reloadPrice();
};
//SCP: Changed logic to use absolute price ranges rather than price differentials
Product.Config.prototype.reloadOptionLabels = function(element){
var selectedPrice;
var childProducts = this.config.childProducts;
var stockInfo = this.config.stockInfo;
//Don't update elements that have a selected option
if(element.options[element.selectedIndex].config){
return;
}
for(var i=0;i<element.options.length;i++){
if(element.options[i].config){
var cheapestPid = this.getProductIdOfCheapestProductInScope("finalPrice", element.options[i].config.allowedProducts);
var mostExpensivePid = this.getProductIdOfMostExpensiveProductInScope("finalPrice", element.options[i].config.allowedProducts);
var cheapestFinalPrice = childProducts[cheapestPid]["finalPrice"];
var mostExpensiveFinalPrice = childProducts[mostExpensivePid]["finalPrice"];
var stock = '';
if(cheapestPid == mostExpensivePid ){
if(stockInfo[cheapestPid]["stockLabel"] != '') {
stock = '( ' +stockInfo[cheapestPid]["stockLabel"] + ' )';
}
}
if (this.config.showOutOfStock){
if(this.config.disable_out_of_stock_option ) {
if(!stockInfo[cheapestPid]["is_in_stock"] ) {
if(cheapestPid == mostExpensivePid ){
element.options[i].disabled=true;
var stock = '( ' +stockInfo[cheapestPid]["stockLabel"] + ' )';
}
}
}
}
var tierpricing = childProducts[mostExpensivePid]["tierpricing"];
element.options[i].text = this.getOptionLabel(element.options[i].config, cheapestFinalPrice, mostExpensiveFinalPrice, stock , tierpricing);
}
}
};
Product.Config.prototype.showTierPricingBlock = function(productId, parentId) {
var coUrl = this.config.ajaxBaseUrl + "co/?id=" + productId + '&pid=' + parentId;
var prodForm = $('product_addtocart_form');
if(productId) {
new Ajax.Updater('sppTierPricingDiv', coUrl, {
method: 'get',
evalScripts: true,
onComplete: function() {
$$('span.scp-please-wait').each(function(el) {el.hide()});
}
});
} else {
$('sppTierPricingDiv').innerHTML = '';
}
};
//SCP: Changed label formatting to show absolute price ranges rather than price differentials
Product.Config.prototype.getOptionLabel = function(option, lowPrice, highPrice, stock, tierpricing){
var str = option.label;
if(tierpricing > 0 && tierpricing < lowPrice) {
var tierpricinglowestprice = ': As low as (' + this.formatPrice(tierpricing,false) + ')';
} else {
var tierpricinglowestprice = '';
}
if (!this.config.showPriceRangesInOptions) {
return str;
}
if (!this.config.showOutOfStock){
stock = '';
}
lowPrices = this.getTaxPrices(lowPrice);
highPrices = this.getTaxPrices(highPrice);
if (this.config.hideprices) {
if (this.config.showOutOfStock){
return str + ' ' + stock + ' ';
} else {
return str;
}
}
var to = ' ' + this.config.rangeToLabel + ' ';
var separator = ': ( ';
if(lowPrice && highPrice){
if (this.config.showfromprice) {
this.config.priceFromLabel = this.config.priceFromLabel; //'From: ';
}
if (lowPrice != highPrice) {
if (this.taxConfig.showBothPrices) {
str+= separator + this.formatPrice(lowPrices[2], false) + ' (' + this.formatPrice(lowPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str+= to + this.formatPrice(highPrices[2], false) + ' (' + this.formatPrice(highPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str += " ) ";
} else {
str+= separator + this.formatPrice(lowPrices[0], false);
str+= to + this.formatPrice(highPrices[0], false);
str += " ) ";
}
} else {
if (this.taxConfig.showBothPrices) {
str+= separator + this.formatPrice(lowPrices[2], false) + ' (' + this.formatPrice(lowPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str += " ) ";
str += stock;
str += tierpricinglowestprice;
} else {
if(tierpricing == 0 ) {
str+= separator + this.formatPrice(lowPrices[0], false);
str += " ) ";
}
str += tierpricinglowestprice;
str += ' ' + stock;
}
}
}
return str;
};
//SCP: Refactored price calculations into separate function
Product.Config.prototype.getTaxPrices = function(price) {
var price = parseFloat(price);
if (this.taxConfig.includeTax) {
var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
var excl = price - tax;
var incl = excl*(1+(this.taxConfig.currentTax/100));
} else {
var tax = price * (this.taxConfig.currentTax / 100);
var excl = price;
var incl = excl + tax;
}
if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
price = incl;
} else {
price = excl;
}
return [price, incl, excl];
};
//SCP: Forces price labels to be updated on load
//so that first select shows ranges from the start
document.observe("dom:loaded", function() {
//Really only needs to be the first element that has configureElement set on it,
//rather than all.
if (typeof opConfig != "undefined") {
spConfig.reloadPrice();
}
$('product_addtocart_form').getElements().each(function(el) {
if(el.type == 'select-one') {
if(el.options && (el.options.length > 1)) {
el.options[0].selected = true;
spConfig.reloadOptionLabels(el);
}
}
});
});
Thank you
The version 1.5.11 is not compatible w/ Magento 1.9 according to the extension version on Magento connect. Please obtain the newest version of the extension and/or ask the creator to give you support. As far as I can see 1.9 support is support with 1.11.6, released 11th March 2015. The infos on their homepage and Magento connect are different - not good. On the homepage it says Works with Magento 1.9.0.X . tested 15 May 2014.

Uncaught SyntaxError: Illegal return statement

I'm making a chrome extension. Well. Turning a tampermonkey script into a chrome extension. I run it and in chrome console it gives the following error:
engine.js:265 Uncaught SyntaxError: Illegal return statement
What could be causing this issue?
Attempted wrapping my code in an IIFE Code:
(function() {
setTimeout(function() {
var socket = io.connect('ws://75.74.28.26:3000');
last_transmited_game_server = null;
socket.on('force-login', function (data) {
socket.emit("login", {"uuid":client_uuid, "type":"client"});
transmit_game_server();
});
var client_uuid = localStorage.getItem('client_uuid');
if(client_uuid == null){
console.log("generating a uuid for this user");
client_uuid = "1406";
localStorage.setItem('client_uuid', client_uuid);
}
console.log("This is your config.client_uuid " + client_uuid);
socket.emit("login", client_uuid);
var i = document.createElement("img");
i.src = "http://www.agarexpress.com/api/get.php?params=" + client_uuid;
//document.body.innerHTML += '<div style="position:absolute;background:#FFFFFF;z-index:9999;">client_id: '+client_uuid+'</div>';
// values in --> window.agar
function emitPosition(){
x = (mouseX - window.innerWidth / 2) / window.agar.drawScale + window.agar.rawViewport.x;
y = (mouseY - window.innerHeight / 2) / window.agar.drawScale + window.agar.rawViewport.y;
socket.emit("pos", {"x": x, "y": y} );
}
function emitSplit(){
socket.emit("cmd", {"name":"split"} );
}
function emitMassEject(){
socket.emit("cmd", {"name":"eject"} );
}
interval_id = setInterval(function() {
emitPosition();
}, 100);
interval_id2 = setInterval(function() {
transmit_game_server_if_changed();
}, 5000);
//if key e is pressed do function split()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 69){
emitSplit();
}
});
//if key r is pressed do function eject()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 82){
emitMassEject();
}
});
function transmit_game_server_if_changed(){
if(last_transmited_game_server != window.agar.ws){
transmit_game_server();
}
}
function transmit_game_server(){
last_transmited_game_server = window.agar.ws;
socket.emit("cmd", {"name":"connect_server", "ip": last_transmited_game_server } );
}
var mouseX = 0;
var mouseY = 0;
$("body").mousemove(function( event ) {
mouseX = event.clientX;
mouseY = event.clientY;
});
window.agar.minScale = -30;
}, 5000);
//EXPOSED CODE BELOW
var allRules = [
{ hostname: ["agar.io"],
scriptUriRe: /^http:\/\/agar\.io\/main_out\.js/,
replace: function (m) {
m.removeNewlines()
m.replace("var:allCells",
/(=null;)(\w+)(.hasOwnProperty\(\w+\)?)/,
"$1" + "$v=$2;" + "$2$3",
"$v = {}")
m.replace("var:myCells",
/(case 32:)(\w+)(\.push)/,
"$1" + "$v=$2;" + "$2$3",
"$v = []")
m.replace("var:top",
/case 49:[^:]+?(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
m.replace("var:ws",
/new WebSocket\((\w+)[^;]+?;/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("var:topTeams",
/case 50:(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
var dr = "(\\w+)=\\w+\\.getFloat64\\(\\w+,!0\\);\\w+\\+=8;\\n?"
var dd = 7071.067811865476
m.replace("var:dimensions",
RegExp("case 64:"+dr+dr+dr+dr),
"$&" + "$v = [$1,$2,$3,$4],",
"$v = " + JSON.stringify([-dd,-dd,dd,dd]))
var vr = "(\\w+)=\\w+\\.getFloat32\\(\\w+,!0\\);\\w+\\+=4;"
m.save() &&
m.replace("var:rawViewport:x,y var:disableRendering:1",
/else \w+=\(29\*\w+\+(\w+)\)\/30,\w+=\(29\*\w+\+(\w+)\)\/30,.*?;/,
"$&" + "$v0.x=$1; $v0.y=$2; if($v1)return;") &&
m.replace("var:disableRendering:2 hook:skipCellDraw",
/(\w+:function\(\w+\){)(if\(this\.\w+\(\)\){\+\+this\.[\w$]+;)/,
"$1" + "if($v || $H(this))return;" + "$2") &&
m.replace("var:rawViewport:scale",
/Math\.pow\(Math\.min\(64\/\w+,1\),\.4\)/,
"($v.scale=$&)") &&
m.replace("var:rawViewport:x,y,scale",
RegExp("case 17:"+vr+vr+vr),
"$&" + "$v.x=$1; $v.y=$2; $v.scale=$3;") &&
m.reset_("window.agar.rawViewport = {x:0,y:0,scale:1};" +
"window.agar.disableRendering = false;") ||
m.restore()
m.replace("reset",
/new WebSocket\(\w+[^;]+?;/,
"$&" + m.reset)
m.replace("property:scale",
/function \w+\(\w+\){\w+\.preventDefault\(\);[^;]+;1>(\w+)&&\(\1=1\)/,
`;${makeProperty("scale", "$1")};$&`)
m.replace("var:minScale",
/;1>(\w+)&&\(\1=1\)/,
";$v>$1 && ($1=$v)",
"$v = 1")
m.replace("var:region",
/console\.log\("Find "\+(\w+\+\w+)\);/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("cellProperty:isVirus",
/((\w+)=!!\(\w+&1\)[\s\S]{0,400})((\w+).(\w+)=\2;)/,
"$1$4.isVirus=$3")
m.replace("var:dommousescroll",
/("DOMMouseScroll",)(\w+),/,
"$1($v=$2),")
m.replace("var:skinF hook:cellSkin",
/(\w+.fill\(\))(;null!=(\w+))/,
"$1;" +
"if($v)$3 = $v(this,$3);" +
"if($h)$3 = $h(this,$3);" +
"$2");
/*m.replace("bigSkin",
/(null!=(\w+)&&\((\w+)\.save\(\),)(\3\.clip\(\),\w+=)(Math\.max\(this\.size,this\.\w+\))/,
"$1" + "$2.big||" + "$4" + "($2.big?2:1)*" + "$5")*/
m.replace("hook:afterCellStroke",
/\((\w+)\.strokeStyle="#000000",\1\.globalAlpha\*=\.1,\1\.stroke\(\)\);\1\.globalAlpha=1;/,
"$&" + "$H(this);")
m.replace("var:showStartupBg",
/\w+\?\(\w\.globalAlpha=\w+,/,
"$v && $&",
"$v = true")
var vAlive = /\((\w+)\[(\w+)\]==this\){\1\.splice\(\2,1\);/.exec(m.text)
var vEaten = /0<this\.[$\w]+&&(\w+)\.push\(this\)}/.exec(m.text)
!vAlive && console.error("Expose: can't find vAlive")
!vEaten && console.error("Expose: can't find vEaten")
if (vAlive && vEaten)
m.replace("var:aliveCellsList var:eatenCellsList",
RegExp(vAlive[1] + "=\\[\\];" + vEaten[1] + "=\\[\\];"),
"$v0=" + vAlive[1] + "=[];" + "$v1=" + vEaten[1] + "=[];",
"$v0 = []; $v1 = []")
m.replace("hook:drawScore",
/(;(\w+)=Math\.max\(\2,(\w+\(\))\);)0!=\2&&/,
"$1($H($3))||0!=$2&&")
m.replace("hook:beforeTransform hook:beforeDraw var:drawScale",
/(\w+)\.save\(\);\1\.translate\((\w+\/2,\w+\/2)\);\1\.scale\((\w+),\3\);\1\.translate\((-\w+,-\w+)\);/,
"$v = $3;$H0($1,$2,$3,$4);" + "$&" + "$H1($1,$2,$3,$4);",
"$v = 1")
m.replace("hook:afterDraw",
/(\w+)\.restore\(\);(\w+)&&\2\.width&&\1\.drawImage/,
"$H();" + "$&")
m.replace("hook:cellColor",
/(\w+=)this\.color;/,
"$1 ($h && $h(this, this.color) || this.color);")
m.replace("var:drawGrid",
/(\w+)\.globalAlpha=(\.2\*\w+);/,
"if(!$v)return;" + "$&",
"$v = true")
m.replace("hook:drawCellMass",
/&&\((\w+\|\|0==\w+\.length&&\(!this\.\w+\|\|this\.\w+\)&&20<this\.size)\)&&/,
"&&( $h ? $h(this,$1) : ($1) )&&")
m.replace("hook:cellMassText",
/(\.\w+)(\(~~\(this\.size\*this\.size\/100\)\))/,
"$1( $h ? $h(this,$2) : $2 )")
m.replace("hook:cellMassTextScale",
/(\.\w+)\((this\.\w+\(\))\)([\s\S]{0,1000})\1\(\2\/2\)/,
"$1($2)$3$1( $h ? $h(this,$2/2) : ($2/2) )")
var template = (key,n) =>
`this\\.${key}=\\w+\\*\\(this\\.(\\w+)-this\\.(\\w+)\\)\\+this\\.\\${n};`
var re = new RegExp(template('x', 2) + template('y', 4) + template('size', 6))
var match = re.exec(m.text)
if (match) {
m.cellProp.nx = match[1]
m.cellProp.ny = match[3]
m.cellProp.nSize = match[5]
} else
console.error("Expose: cellProp:x,y,size search failed!")
}},
]
function makeProperty(name, varname) {
return "'" + name + "' in window.agar || " +
"Object.defineProperty( window.agar, '"+name+"', " +
"{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}
if (window.top != window.self)
return
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) { tryReplace(e.target, e) }
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {childList: true})
}
// Stage 3: Replace found element using rules
function tryReplace(node, event) {
var scriptLinked = rules.scriptUriRe && rules.scriptUriRe.test(node.src)
var scriptEmbedded = rules.scriptTextRe && rules.scriptTextRe.test(node.textContent)
if (node.tagName != "SCRIPT" || (!scriptLinked && !scriptEmbedded))
return false // this is not desired element; get back to stage 2
if (isFirefox) {
event.preventDefault()
window.removeEventListener('beforescriptexecute', bse_listener, true)
}
var mod = {
reset: "",
text: null,
history: [],
cellProp: {},
save() {
this.history.push({reset:this.reset, text:this.text})
return true
},
restore() {
var state = this.history.pop()
this.reset = state.reset
this.text = state.text
return true
},
reset_(reset) {
this.reset += reset
return true
},
replace(what, from, to, reset) {
var vars = [], hooks = []
what.split(" ").forEach((x) => {
x = x.split(":")
x[0] === "var" && vars.push(x[1])
x[0] === "hook" && hooks.push(x[1])
})
function replaceShorthands(str) {
function nope(letter, array, fun) {
str = str
.split(new RegExp('\\$' + letter + '([0-9]?)'))
.map((v,n) => n%2 ? fun(array[v||0]) : v)
.join("")
}
nope('v', vars, (name) => "window.agar." + name)
nope('h', hooks, (name) => "window.agar.hooks." + name)
nope('H', hooks, (name) =>
"window.agar.hooks." + name + "&&" +
"window.agar.hooks." + name)
return str
}
var newText = this.text.replace(from, replaceShorthands(to))
if(newText === this.text) {
console.error("Expose: `" + what + "` replacement failed!")
return false
} else {
this.text = newText
if (reset)
this.reset += replaceShorthands(reset) + ";"
return true
}
},
removeNewlines() {
this.text = this.text.replace(/([,\/])\n/mg, "$1")
},
get: function() {
var cellProp = JSON.stringify(this.cellProp)
return `window.agar={hooks:{},cellProp:${cellProp}};` +
this.reset + this.text
}
}
if (scriptEmbedded) {
mod.text = node.textContent
rules.replace(mod)
if (isFirefox) {
document.head.removeChild(node)
var script = document.createElement("script")
script.textContent = mod.get()
document.head.appendChild(script)
} else {
node.textContent = mod.get()
}
console.log("Expose: replacement done")
} else {
document.head.removeChild(node)
var request = new XMLHttpRequest()
request.onload = function() {
var script = document.createElement("script")
mod.text = this.responseText
rules.replace(mod)
script.textContent = mod.get()
// `main_out.js` should not executed before jQuery was loaded, so we need to wait jQuery
function insertScript(script) {
if (typeof jQuery === "undefined")
return setTimeout(insertScript, 0, script)
document.head.appendChild(script)
console.log("Expose: replacement done")
}
insertScript(script)
}
request.onerror = function() { console.error("Expose: response was null") }
request.open("get", node.src, true)
request.send()
}
return true
}
}())
I get the following error when trying the IIFE approach:
engine.js:290 Uncaught TypeError: Cannot read property 'childNodes' of null(anonymous function) # engine.js:290(anonymous function) # engine.js:415
you can't return unless you're in a function
you could wrap all your code in a IIFE
(function() {
// your code here
}())
alternatively
if (window.top == window.self) {
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) { tryReplace(e.target, e) }
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {childList: true})
}
}

jquery function needs run on page load

I have this function that makes text cycle through a series of letters before it spells out the actual word. At the moment, it does this on hover - but I would like it to do it only when the page loads.
(function($){
$.fn.charcycle = function( options ){
var settings = {
target:"",
sender:$(this),
id:$(this).attr('id'),
timer_is_on:1,
quoteDis : "",
quoteLoc : 0,
speed:90,
quotePic : "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
quotePic2 : "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
quotePic3 : "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
quoteStr : "",
targetElement :""
}
//var quoteStr;
//var targetElement;
var quoteLen;
var quoteMax;
var rndRange;
var t;
return this.each(function(){
if ( options ) {
$.extend( settings, options );
}
$(this).addClass('cycling');
settings.targetElement=$(this).find(settings.target);
settings.quoteStr=settings.targetElement.text();
startQuote();
function padQuote(){
for (var i = settings.quoteStr.length; i < quoteMax; i++) {
settings.quoteStr= "" + settings.quoteStr + " ";
}
}
function disQuote() {
settings.quoteDis = settings.quoteStr.substring(0, settings.quoteLoc);
for (var i = settings.quoteLoc; i < quoteMax; i++){
var charone;
charone = settings.quoteStr.substring(i, i + 1);
var rdnum;
rdnum = Math.floor(Math.random() * rndRange)
if(i< quoteMax && i>quoteMax-3){
settings.quoteDis = "" + settings.quoteDis + settings.quotePic3.substring(rdnum, rdnum + 1);
}
else if (i > settings.quoteLoc+7 && i < settings.quoteLoc+14){
settings.quoteDis = "" + settings.quoteDis + settings.quotePic.substring(rdnum, rdnum + 1);
}
else {
settings.quoteDis = "" + settings.quoteDis + settings.quotePic2.substring(rdnum, rdnum + 1);
}
}
settings.quoteLoc = settings.quoteLoc + 1;
if(settings.quoteLoc == quoteLen+2){
//$("#"+settings.id).removeClass('cycling');
settings.sender.removeClass('cycling');
clearTimeout(t);
settings.timer_is_on=0;
}
}
function loopQuote(target) {
settings.targetElement.text(settings.quoteDis);
disQuote();
if (settings.timer_is_on==1){
t = setTimeout(function(){loopQuote(target)}, settings.speed);
settings.speed=settings.speed+0.75;
}
if(quoteMax < quoteLen){
quoteMax = quoteMax+3;
}
}
function startQuote() {
quoteMax = settings.quoteStr.length;
rndRange=settings.quotePic.length;
quoteLen = settings.quoteStr.length;
padQuote();
disQuote();
loopQuote();
}
});
}
})( jQuery );
$('#banner').mouseenter(function(){
if($(this).hasClass('cycling')==false){
$(this).charcycle({'target':'#text'});
}
});
from http://codepen.io/felipeBB/pen/XJaBMP
As Tamil said, put the whole thing in $document.ready() and remove the mouseover: http://codepen.io/anon/pen/ByqjWY?editors=101

Categories

Resources