"Cannot read property 'match' of null" - javascript

I have that script:
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, " "));
}
var dynamicContent = getParameterByName('utm_term');
$(document).ready(function() {
if (dynamicContent.match(/buy/i)) {
$('#buy').show();
}
else {
$('#default-content').show();
}
});
When in url there is any parametr it's working fine and else working, #deafult-content showing.
Problem that when i have clean url without parametr #default-content don't showing because "Cannot read property 'match' of null".
Any idea how to fix this?

you are returning null for !results, which you can then not match against.
try combining your two checks and return an empty string:-
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 || !results[2])
return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var dynamicContent = getParameterByName('utm_term');
$(document).ready(function() {
if (dynamicContent.match(/buy/i)) {
$('#buy').show();
} else {
$('#default-content').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="default-content" style="display:none;">test</p>

Related

OPEN (on click) an specific URL from a 'complex' URL

I have a complex string (URL) that is a link .
How to OPEN on click a specific URL from that URL/string... NOT the 'parent' URL?
Parent URL looks like this:
http://www.randomsite.com & randomtext & URL I need
.
Thank you.
On the assumption you mean get the url from the query string e.g. http://www.randomsite.com?foo=bar&url=http://www.url-i-want.com
You could do this:
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, " "));
}
var url = getParameterByName('url');
window.location.href = url;
ref: https://stackoverflow.com/a/901144/905653
Here is a simple solution
function getUrlVar(stringUrl, name) {
for (var value of stringUrl.split("?")[1].split("&")) {
var valueArr = value.split("=");
if (valueArr[0] === name) {
return valueArr[1];
}
}
return false;
}
var complexUrl = "http://www.whatever.com?lang=en&url=http://www.anyurlwhatsoever.com&test=loremipsum";
console.log(getUrlVar(complexUrl, "test"));
console.log(getUrlVar(complexUrl, "lang"));
console.log(getUrlVar(complexUrl, "url"));
console.log(getUrlVar(complexUrl, "asdasd"));
...Almost done... ! ;-)
But...I will be more 'specific':
ParentURL = URL1+random-text+URL-I-want
What I want to do is...on click on the link/ParentURL to open the link/URL-I-want, NOT the link/ParentURL (I think the best "suggestion" is...to 'specify' somehow a 'part' of the URL1...to be sure the URL of the opened window will be URL-I-want, NOT the URL1) !
Thank you .
function getUrlVar(stringUrl, name) {
for (var value of stringUrl.split("?")[1].split("&")) {
var valueArr = value.split("=");
if (valueArr[0] === name) {
return valueArr[1];
}
}
return false;
}
var complexUrl = "http://www.whatever.com?lang=en&url=http://www.anyurlwhatsoever.com&test=loremipsum";
console.log(getUrlVar(complexUrl, "test"));
console.log(getUrlVar(complexUrl, "lang"));
console.log(getUrlVar(complexUrl, "url"));
console.log(getUrlVar(complexUrl, "asdasd"));

Get very specific url

I want to get very specific string over my url to add as parameter in js:
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token=', usuario,
completado,
fallo);
}
URL
http://localhost:55728/Cliente/#/cambiarContrasena.html?Token=e12009cf-d48d-42e7-ba43-83b5082019bb
I want to get only Guid afrer Token= like:
e12009cf-d48d-42e7-ba43-83b5082019bb
I try using:
var url = (location.pathname + location.search).substr(1);
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
completado,
fallo);
}
But I get
http://localhost:55718/api/usuario/cambiarContrasena?token=Cliente/
I try too:
var guid = url.substr(url.indexOf('Token=') + 6);
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token='+guid, usuario,
completado,
fallo);
}
But I get
Uncaught ReferenceError: url is not defined
What I need to do to get only parameters after Token= ?
I try as this question:
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, " "));
}
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token='+getParameterByName, usuario,
completado,
fallo);
}
But I get an error:
POST
http://localhost:55718/api/usuario/cambiarContrasena?token=function%20getPa…%20%20var%20regex%20=%20new%20RegExp(%22[?&]%22%20+%20name%20+%20%22(=([^&
400 (Bad Request)
just try this :
var url = window.location.hash.split('?Token=')[1];
var guid = url || '';

Dynamically create a find query and have it trigger helper

What I have is a collection. By default the whole collection is shown on the page in a table. The user can then narrow down the results by entering in filter data in 1 or multiple textboxes.
So I have spent the last several hours trying to make this work reactively but failing miserably. The helper is below:
Template.localBoardTemplate.helpers({
localDelivery: function (){
return localBoardColl.find(query);
}
});
Now I have keyup events on the individual textboxes that all trigger the same function to dynamically build the query:
function loadBoardRecords(){
var query = {};
if($('input:text[name=localBoardTripNumSetting]').val() != ""){
query['tripNumber'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTripNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardLoadNumSetting]').val() != ""){
query['orderLoadNum'] = {$regex: new RegExp('^' + $('input:text[name=localBoardLoadNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardEquipmentSetting]').val() != ""){
query['equipmentTypeName'] = {$regex: new RegExp('^' + $('input:text[name=localBoardEquipmentSetting]').val(), 'i')};
}
if($('input:text[name=localBoardCustomerSetting]').val() != ""){
query['Customer'] = {$regex: new RegExp('^' + $('input:text[name=localBoardCustomerSetting]').val(), 'i')};
}
if($('input:text[name=localBoardTrailerNumSetting]').val() != ""){
query['trailerNum'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTrailerNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardPUCitySetting]').val() != ""){
query['puCity'] = {$regex: new RegExp('^' + $('input:text[name=localBoardPUCitySetting]').val(), 'i')};
}
if($('input:text[name=localBoardPUStateSetting]').val() != ""){
query['puState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardPUStateSetting]').val(), 'i')};
}
if($('#localBoardPUDateSetting').val() != ""){
puDate = moment($('#localBoardPUDateSetting').val(), "MM-DD-YYYY").toDate();
query['puDate'] = puDate;
}
if($('input:text[name=localBoardDELCitySetting]').val() != ""){
query['delCity'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELCitySetting]').val(), 'i')};
}
if($('input:text[name=localBoardDELStateSetting]').val() != ""){
query['delState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELStateSetting]').val(), 'i')};
}
if($('#localBoardDELDateSetting').val() != ""){
delDate = moment($('#localBoardDELDateSetting').val(), "MM-DD-YYYY").toDate();
query['delDate'] = delDate;
}
}
Now I have tried using a session variable to hold the query this failed because you can't have nested objects in the session variables. I then tried a package called ReactiveObj and that I couldn't get working either. Heck I even tried a ReactiveArr but that isn't reactive unless you .list it and that doesn't work for the query in the find.
This can't be this hard of a problem and I have probably overlooked something minor. I am hoping someone can point me to the write package or solution for this problem.
A quick-n-dirty code with ReactiveVar
var buildQuery = function(formId) {
// put the code in the loadBoardRecords with the form id
// and return the query
return query;
}
Template.layout.helpers({
localDelivery: function (){
return Template.instance()['resultSet'].get();
}
});
Template.layout.events({
'click .searchButton': function() {
var formId = $(...); // get the id for the form
var cursor = localBoardColl.find(search(formId));
Template.instance()['resultSet'].set(cursor);
}
});
Template.layout.created = function () {
this['resultSet'] = new ReactiecVar(null);
}
Actually you CAN store nested objects in Session variable.
On helpers:
Template.localBoardTemplate.helpers({
localDelivery: function (){
var query = Session.get('QUERY') || {};
return localBoardColl.find(query);
}
});
On events:
function loadBoardRecords(){
var query = Session.get('QUERY') || {};
if($('input:text[name=localBoardTripNumSetting]').val() != ""){
query['tripNumber'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTripNumSetting]').val(), 'i')};
}
.
.
.
.
.
if($('#localBoardDELDateSetting').val() != ""){
delDate = moment($('#localBoardDELDateSetting').val(), "MM-DD-YYYY").toDate();
query['delDate'] = delDate;
}
Session.set('QUERY',query);
}
That is totally possible.
I have solved this through a few bit more trial and error and the help of Thai Trans answer. I used a reativevar variable to store an object. The correct code is as follows:
Helper:
Template.localBoardTemplate.helpers({
localDelivery: function (){
return localBoardColl.find(Template.instance().searchQuery.get());
}
});
The function that creates the query and stores it in the reacvtive-var:
function loadBoardRecords(template){
var query = {};
if($('input:text[name=localBoardTripNumSetting]').val() != ""){
query['tripNumber'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTripNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardPUStateSetting]').val() != ""){
query['puState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardPUStateSetting]').val(), 'i')};
}
if($('#localBoardPUDateSetting').val() != ""){
puDate = moment($('#localBoardPUDateSetting').val(), "MM-DD-YYYY").toDate();
query['puDate'] = puDate;
}
if($('input:text[name=localBoardDELCitySetting]').val() != ""){
query['delCity'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELCitySetting]').val(), 'i')};
}
if($('input:text[name=localBoardDELStateSetting]').val() != ""){
query['delState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELStateSetting]').val(), 'i')};
}
if($('#localBoardDELDateSetting').val() != ""){
delDate = moment($('#localBoardDELDateSetting').val(), "MM-DD-YYYY").toDate();
query['delDate'] = delDate;
}
template.searchQuery.set( query );
}
This works perfectly. It also still allows for the reactive collection updates even during a users search.

error in google apps script if no file upload is specified

I'd like to give the user the option to upload a file, but it's not strictly necessary. This script seems to glitch if there is no file specified. How can I fix that? It seems like the line it really doesn't like is: var file1 = folder.createFile(blob1);
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "Student Files";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var id = "1L2syfAOm6MiYPtWuWwFZFK_ZtLpLOjNx9EpjHh2IKUY";
var ss = SpreadsheetApp.openById(id);
var blob1 = form.myFile1;
var file1 = folder.createFile(blob1);
file1.setDescription("Uploaded by " + form.myName);
var f1 = '=HYPERLINK("' + file1.getUrl() + '", "File 1")';
Logger.log("test");
var sheet = ss.getSheetByName('Sheet1');
sheet.appendRow([form.myName, form.addy, form.twitter, form.status, form.what, form.projTitle,
form.brief, form.full, form.role, form.date, form.website, f1]);
return "Your entry was successfully uploaded!";
} catch (error) {
return error.toString();
}
}
EDIT: Thanks to suggestion, here is what I ended up with (allows for three optional files)
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "Student Files";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var id = "1L2syfAOm6MiYPtWuWwFZFK_ZtLpLOjNx9EpjHh2IKUY";
var ss = SpreadsheetApp.openById(id);
var blob1 = form.myFile1;
var blob2 = form.myFile2;
var blob3 = form.myFile3;
// check for empty blobs on file attachment uploads
if( !isEmpty(blob1) ) {
var file1 = folder.createFile(blob1);
file1.setDescription("Uploaded by " + form.myName);
var f1 = '=HYPERLINK("' + file1.getUrl() + '", "File 1")';
} else {
var f1 = "nada";
}
if( !isEmpty(blob2) ) {
var file2 = folder.createFile(blob2);
file2.setDescription("Uploaded by " + form.myName);
var f2 = '=HYPERLINK("' + file2.getUrl() + '", "File 2")';
} else {
var f2 = "nada";
}
if( !isEmpty(blob3) ) {
var file3 = folder.createFile(blob3);
file3.setDescription("Uploaded by " + form.myName);
var f3 = '=HYPERLINK("' + file3.getUrl() + '", "File 3")';
} else {
var f3 = "nada";
}
Logger.log("test");
var sheet = ss.getSheetByName('Sheet1');
sheet.appendRow([form.myName, form.addy, form.twitter, form.status, form.what, form.projTitle,
form.brief, form.full, form.role, form.date, form.website, f1, f2, f3]);
return "Your entry was successfully uploaded!";
} catch (error) {
return error.toString();
}
}
// New stuff. A function that tests if a string is empty or null
function isEmpty(str) {
return (!str || 0 === str.length);
}
Can't you just test if a name is specified? I.e. add an if statement that checks that the name is not null and not empty... You might also want to test for things like slashes, in case the user is trying to create subdirectories...
I lifted a test for null or empty from here, but you can roll your own.
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "Student Files";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var id = "1L2syfAOm6MiYPtWuWwFZFK_ZtLpLOjNx9EpjHh2IKUY";
var ss = SpreadsheetApp.openById(id);
var blob1 = form.myFile1;
if( !isEmpty(blob1) ) {
var file1 = folder.createFile(blob1);
file1.setDescription("Uploaded by " + form.myName);
var f1 = '=HYPERLINK("' + file1.getUrl() + '", "File 1")';
Logger.log("test");
var sheet = ss.getSheetByName('Sheet1');
sheet.appendRow([form.myName, form.addy, form.twitter, form.status, form.what, form.projTitle,
form.brief, form.full, form.role, form.date, form.website, f1]);
return "Your entry was successfully uploaded!";
} else {
return "No file name specified!";
}
} catch (error) {
return error.toString();
}
}
// New stuff. A function that tests if a string is empty or null
function isEmpty(str) {
return (!str || 0 === str.length);
}
Just check if blob1 is null, if it is then trhow an exception.

Uncaught TypeError: Cannot read property 'getSelected' of undefined (Chrome-Extension )

Hi i am making google chrome extension and stucked with error
Uncaught TypeError: Cannot read property 'getSelected' of undefined
My code is below
called function getQueryString(); inside if statement is creating error
key_event.js
if (window == top) {
window.addEventListener('keyup', doKeyPress, false); //add the keyboard handler
}
trigger_key = 37;
function doKeyPress(e){
if (e.ctrlKey && e.keyCode == 37)
{
alert("leftpressed");
getQueryString();
}
else if(e.ctrlKey && e.keyCode == 39){ // if e.shiftKey is not provided then script will run at all instances of typing "G"
alert("rightpressed");
getQueryString();
}
}
function getParameterByName(name,urlPara) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(urlPara);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function getQueryString() {
chrome.tabs.getSelected(null, function(tab) {
var tab = tab.url;
var queryString = {};
var substr = tab.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);
var current = getParameterByName('page',tab);
var reExp = 'page=' + current;
current = parseInt(current, 10)-1;
var newUrl = tab.replace(reExp, 'page=' + current);
console.log(newUrl);
chrome.runtime.sendMessage({redirect: newUrl});
});
}
help can bring cheers
Your script key_event.js is a content script. It is running in the context of the website rather than the extension context. As a result it cannot use all of the chrome API (like chrome.tabs).
In order to get the current website URL from inside the website context, you can use window.location.href. You can also get the query string using window.location.search. So no need to query chrome.tabs here.
Something in the lines of
var tabURL = window.location.href;
var queryString = window.location.search;

Categories