Google Custom Site Search - Promotion Not Displaying - javascript

I'm using the standard custom search installation. I have promotions setup to my account.
I have the following:
google.load('search', '1', { language: 'en', style: google.loader.themes.MINIMALIST });
google.setOnLoadCallback(function () {
var customSearchOptions = {};
customSearchOptions[google.search.Search.RESTRICT_EXTENDED_ARGS] = { 'as_sitesearch': '' };
var customSearchControl = new google.search.CustomSearchControl('CSE-UNIQUE-ID', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setAutoComplete(true);
customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
customSearchControl.draw('cse', options);
customSearchControl.execute(getParameterByName("q"));
}, true);
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
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, " "));
}
}
I am setting the javascript object field: as_sitesearch via a CMS, so the code can be used across sites. When the field is populated with i.e ".example.com" the promotions do not display in the search results. They do on the other hand display in the auto-complete.
When the as_sitesearch field is empty the promotions display? Why is this?
Thanks

It appears that when a link for a promotion is linking to a sub-domain or another domain totally, the search filter removes the promotion from the results as its not within the given domain in the as_sitesearch field.
Although it appears the autocomplete search does not use the filter given and therefore displays the promotions.

Related

Is there way start a loop in a certain date range

I have a sheet that is dynamically updating with leads from my marketing campaign. Currently, it has over 9K rows and will continue to grow.
I need to check values for Col F for leads that came in today; however, when I run a loop, it takes too long since it has 9k+ rows.
I want to run a loop for rows that have today's date only. Is there a way to have my script efficiently look for today's date first (without having to loop through 9k rows), and then start my loop?
Below is what I had originally. The code would start from the top of the sheet and look at Col F values and then email me if a cell had only "az-" instead of a full location value. Content below has been modified for privacy
function Google_Check_Lead_Values() {
var title = "Google | Leads"
var app = SpreadsheetApp;
var Def_url = ("website")
///EDIT ^ URL
var ss = app.openByUrl(Def_url).getSheetByName("Google | Leads");
var last_row = ss.getLastRow();
for (i = 1;i <=last_row; i++) {
var location = ss.getRange(i,6).getValue();
var location_len = location.length;
if (location_len <= 3){
MailApp.sendEmail({
to: "email1",
//cc: "email2",
subject: "Discrepancy found on " + title,
htmlBody:"Hi Team, <br>This is an automated notifcation to let you know that an issue was found on " + title + ". Please take a look at the sheet linked below: <br><br> email"
});//end of email
}//end of if
}//end of for
}//end of function
Try it like this:
function Google_Check_Lead_Values() {
const title = "Google | Leads"
const ss = SpreadsheetApp.openByUrl("url")
const sh = SpreadsheetApp.openByUrl(Def_url).getSheetByName(title);
const dt = new Date();
const dtv = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()).valueOf();
const vs = sh.getDataRange().getValues();
vs.forEach(r => {
let loc = r[5].toString();
let d = new Date(r[0]);
let dv = new Date(d.getFullYear(),d.getMonth(),d.getDate()).valueOf();
if( dv == dtv && loc.length < 4) {
MailApp.sendEmail({ to: "email1", subject: "Discrepancy found on " + title, htmlBody: "Hi Team, <br>This is an automated notifcation to let you know that an issue was found on " + title + ". Please take a look at the sheet linked below: <br><br> email", })
}
});
}
I believe your goal is as follows.
You want to reduce the process cost of the search of value from a large sheet.
You want to achieve this using Google Apps Script.
In your situation, by searching the values from the columns "A" and "F", you want to send emails.
In order to search the values from a sheet, there are several methods. Using for loop, TextFinder and query language. In my test, when the query language is used, the process cost was the lowest of these 3 patterns. So, in this answer, I would like to propose to search the values using use the query language. Ref
Sample script:
function Google_Check_Lead_Values() {
var title = "Google | Leads"
var Def_url = "###"; // Please use your Spreadsheet URL.
var ss = SpreadsheetApp.openByUrl(Def_url);
const spreadsheetId = ss.getId();
const today = new Date();
const tommorow = new Date();
tommorow.setDate(tommorow.getDate() + 1);
const vToday = Utilities.formatDate(today, Session.getScriptTimeZone(), "yyyy-MM-dd");
const vTommorow = Utilities.formatDate(tommorow, Session.getScriptTimeZone(), "yyyy-MM-dd");
const sheetName = "Google | Leads";
const query = `SELECT * WHERE A >= DATE '${vToday}' AND A < date '${vTommorow}' AND E = 'az-'`;
const url = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/gviz/tq?sheet=${sheetName}&tqx=out:csv&tq=${query}`;
const res = UrlFetchApp.fetch(encodeURI(url), { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } });
const [, ...values] = Utilities.parseCsv(res.getContentText());
if (values.length == 0) return;
values.forEach(_ => {
MailApp.sendEmail({
to: "email1",
//cc: "email2",
subject: "Discrepancy found on " + title,
htmlBody: "Hi Team, <br>This is an automated notifcation to let you know that an issue was found on " + title + ". Please take a look at the sheet linked below: <br><br> email"
});
});
}
When this script is run, the today date values are searched from the column "A", and also it searches whether the cell value of column "F" is the value of az-. When the values are found, the emaiil is sent. In this case, from your showing script, for example, when 2 rows are found, 2 emails are sent.
If you know the Spreadsheet ID, you can also directly use it to const spreadsheetId = ss.getId(); like const spreadsheetId = "###SpreadsheetID###";.
In this sample script, about the search of the column "F", it seaches whether the value is az-. But, if you want to search the length of cell value, please modify as follows.
From
const query = `SELECT * WHERE A >= DATE '${vToday}' AND A < date '${vTommorow}' AND E = 'az-'`;
To
const query = `SELECT * WHERE A >= DATE '${vToday}' AND A < date '${vTommorow}' AND E MATCHES '^.{0,3}$'`;
References:
Query Language Reference (Version 0.7)
Related thread.
https://stackoverflow.com/a/56663884

Storing parsed URL in Cookie (not storing the entire value)

TL;DR: I am forced to use a javascript solution to store a URL parameter as a cookie, but when the function runs, it only stores the first 5 characters of the value I need.
I am working on implementing affiliate sales tracking across domains. As stated above, I need to store a value from a URL in a cookie so that I can pull it into a separate (functioning) script later. On my primary domain, I was able to do this with a simple .php script, but the third-party platform we use for our sales doesn't allow me to run .php scripts, so I found a javascript function that seemed to be working prior to today. That said, prior to today I was using test parameters that were only numerical (1234567890, etc.).
Here is an example of the kind of URL and parameter being used:
https://subdomain.platform-domain.com/subscribe/Product_ID?irclickid=QW6QnmxpdxySWmnwUx0Mo6bwUkEx5HXJxUUm0c0
This is the function I've been using successfully up until now:
function getParameterByName(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
results = regex.exec(location.search);
return results === null
? ''
: decodeURIComponent(results[1].replace(/\+/g, ' '));
}
var results = getParameterByName('irclickid');
if (results != null || results != '') {
Cookies.set('irclickid', results, { expires: 30 });
}
For some reason, the function now only stores the first 5 characters of the value, or "QW6Qn" in this case. Any help or direction on how to make this work correctly is appreciated.
Resolution:
I found a function that was more apt for what I needed here on stackoverflow: How to get parameter name?, and replaced the first part of my javascript with the following, and it is now working as expected!
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
The last section remained the same:
var results = getParameterByName('irclickid');
if (results != null || results != '') {
Cookies.set('irclickid', results, { expires: 30 });
}
Thank you to those that offered help and insight.
const url = new URL('https://subdomain.platform-domain.com/subscribe/Product_ID?irclickid=QW6QnmxpdxySWmnwUx0Mo6bwUkEx5HXJxUUm0c0')
document.cookie = `irclickid=${url.searchParams.get('irclickid')}; expires=...`
You can see on https://caniuse.com/url if all required browsers support URL.

Returning future weekday excluding holidays

I should preface by saying I know nothing about scripting. I found this script online that fit my needs, so I was able to re-purpose it for my project. Anyway, this script takes Google form submissions, populates a Google doc template, that template gets copied, converted to PDF, and placed in a specific folder on my Google Drive.
So my question is, I have a simple line that pulls the current date when the script gets run, but I also need some code that can calculate the current date plus 5 weekdays (which should exclude weekends), but I also need it to exclude defined holidays. Any help would be greatly appreciated.
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email_address = "";
var job_name = e.values[1];
var ship_to = e.values[11];
var address = e.values[12];
var order_count = e.values[7];
var program = e.values[2];
var workspace = e.values[3];
var offer = e.values[4];
var sort_1 = e.values[5];
var sort_2 = e.values[6];
var print_services = e.values[10];
var priority = e.values[13];
var notes = e.values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
You can use the below function to get future date which excludes weekends and if any holiday declared in the array.
function addDates() {
var date = new Date(); // yor form date
var hodiday = ["08/09/2017","08/15/2017"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if(days > 0 ){
while (counter < days) {
date.setDate(date.getDate() + 1 );
var check = date.getDay();
var holidayCheck = hodiday.indexOf(Utilities.formatDate(date, "GMT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}

How to pass a variable into a the src of an iframe using Google Maps

I'm building an app that suggests a random location to the user, and displays a google map on the page with that location.
The tutorial I'm following suggested using the iframe embed code to do this.
How can I take the variable created for the random location, 'barname', and pass that into the src url of the iframe?
Here is the code from the :
<script>
// Our List of Bars
var bars = [
'Siggys',
'Blind Tiger',
'Zum Schneider',
'One Month',
'Home Sweet Home',
'Union Pool'
];
// Our List of Friends
var friends = [
'Mattan',
'Chris',
'Lee',
'Casey',
'that girl you forgot to text back',
'Kayne West',
'Gerard'
];
var randomNumber = Math.floor(Math.random()*bars.length);
var barname = bars[randomNumber];
var friendname = friends[randomNumber];
document.write("How about you go to <strong>" + barname + "</strong> with <strong>" + friendname + "</strong>?");
</script>
While I know there might be other ways to do this using the Google MAPS API for Javascript, I'm trying to figure out a simple solution using the iframe embed code, since that is what the tutorial suggested.
Thanks for reading.
Do you mean something like GET parameter passing?
Here's what I tried: https://jsfiddle.net/4gb4p3sq/1/
//Made an iframe in my html named locationFrame.
//This takes locationFrame's src.
var frameSrc = document.getElementById("locationFrame").src;
//The src ends with a "?q=" which will be our GET parameter.
frameSrc = frameSrc + barname;
//example output: https://www.google.com/search??q=Siggys
alert(frameSrc);
//then add this function to your iframe to get the parameter
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
//our GET parameter is called q and our src is stored at frameSrc
var variableFromFirstHtml = getParameterByName('q', frameSrc);
//alert to check if we're getting barname
alert(variableFromFirstHtml);
})();

get only part of current url and redirect with javascript

I need get only this part of current url and redirect after 5 seconds...
example of current url:
http://www.page.com/?archive=filename
i need get only filename and put in javascript code
here my code:
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script type="text/javascript">
var country,url;
country = geoip_country_code()
if(country=="US"){
url="http://www.page.com/1.php?archive=filename";
} else if (country == "UK") {
url="http://www.page.com/2.php?archive=filename";
} else if (country == "ES") {
url="http://www.page.com/3.php?archive=filename";
}
setTimeout("location.href = url;",5000);
</script>
please i need help with this code, thanks.
you can use the code posted here:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var country,
url,
codemap = {
US: 1,
UK: 2,
ES: 3
};
url = "http://www.page.com/" + codemap[geoip_country_code()] + ".php?archive=" + getParameterByName('archive');
setTimeout(function () { location.href = url; },5000);
Here's a previous question on parsing query strings in JavaScript. That one's already marked as a duplicate, so there's undoubtedly more info out there. If this doesn't help, the keywords you want to search for are "Parse query string in JavaScript".
Parse query string in JavaScript

Categories

Resources