URL API parser alternative for Google Scripts - google-apps-script

The javascript used by Google Scripts does not include the URI API library for parsing URLs. It also does not support complex (perl-like backwards looking) regular expressions. As far as I know you can't import public libraries. This makes it hard, verbose and unreliable to parse out URL elements.
However it does support web calls through URLFetchApp and the REST API. Is there a parsing server out in the internet that hosts the URI API, which can be called by URLFetchApp or using the built in REST API? I can not find one easily. Other solutions welcome.
I have a working solution only for US based URLs. International URLs break my regEx. I prefer using a robust solution not dependent on regEx.
If you want to know the problem dealing with....
I need to compare two URLs and see if the 2nd url is a on a subdomain, or directory or same as the home page.
function scoreURL (urlOne,urlTwo){
let regexSubdomain = /(?:http[s]?:\/\/)?([^\/\s]+)(\/.*)?/;
var urlOneArray = urlOne.split(regexSubdomain);
var urlTwoArray = urlTwo.split(regexSubdomain);
var subdomainOne = urlOneArray[1].replace(new RegExp('www.','i'),'')
var subdomainTwo = urlTwoArray[1].replace(new RegExp('www.','i'),'')
// return -1 if landing page is on sub domais, 0 if landing page is separate page , 1 if landing page is home page
if (subdomainOne === subdomainTwo) {
if (urlOneArray[2] === urlTwoArray[2])
{return (1);} else {return(0);}
} else return (-1);
}

The basic URL api links to a polyfill core-js module.
The URL polyfill uses multiple require statements that are not directly supported in apps script.
You can manually copy paste all required files from the parent directory and remove all required dependencies OR
Use webpack in your local nodejs to transpile the polyfill
install webpack and corejs
mkdir webpack
cd webpack
npm init -y
npm install webpack webpack-cli --save-dev
npm install --save core-js#3.18.3
src/index.js:
import 'core-js/web/url'
Bundle with webpack
npx webpack
Copy the resulting bundled js(in dist/main.js) to a file(url.gs) in apps script.
You'll now be able to use URL, URLSearchParams in global scope.

Related

How to link an html form to a batch file?

I have this batch file, which is supposed to run the npm package Nativefier:
SET /P _inputname= Please enter a URL:
nativefier %_inputname%
I would like to run this from an electron app's index.html. I have previously tried using an html form and using the following javascript:
$("form").submit(function(){
var WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run ("Experiment.bat");
});
However, this has not seemed to work. Does anyone have a better solution? Any help would be greatly appreciated!
(I am doing this with the intent of building a desktop application, it is not for a webpage)
The ActiveXObject API you're using is only available in old versions of Internet Explorer, and not Chromium (which is the browser engine behind Electron).
In general, in order to run a native executable from Electron, you want to use Node.js child_process module. It should look something like this. Make sure that webPreferences.nodeIntegration is true in your BrowserWindow options so that you can use Node APIs in your renderer process.
const { spawn } = require("child_process");
$("form").submit(() => {
const process = spawn("path/to/executable.bat");
});
Note that you don't necessarily need a .bat file at all.
If you have nativefier as a dependency, you could grab the executable from your node_modules folder and spawn that directly. For instance (assuming that your form submission contains the URL required for Nativefier to run:
const { spawn } = require("child_process");
$("form").submit((myURL) => {
const process = spawn(`/node_modules/path/to/nativefier/binary ${myURL}`);
});

Using includeData Tag with nunjucks templating

I am using the automated workflow with gulp to build html and css from nunjucks templates based on this: https://github.com/uxmoon/automate-workflow
And I now want to include json data stored in files to access them in my components. There is a plugin called "includeData" that should do the trick:
https://github.com/VincentLeung/nunjucks-includeData
I tried to include this into the process, but it does not work.
What I did so far:
I added a file called "nunjucks-includedata.js" into the tasks folder where the gulp tasks are located.
var nunjucks = require('nunjucks'),
includeData = require('nunjucks-includeData'),
gulpnunjucks = require('gulp-nunjucks');
var templates = 'app/templates'; //Set this as the folder that contains your nunjuck files
var env = new nunjucks.Environment(new nunjucks.FileSystemLoader(templates));
includeData.install(env);
gulp.task('pages', function() {
// Gets .html files. see file layout at bottom
return gulp.src([templates + '/*.html', templates + '/**/*.html'])
// Renders template with nunjucks and marked
.pipe(gulpnunjucks.compile("", {env: env}))
// output files in dist folder
.pipe(gulp.dest(dist))
});
But it does not work. I get an error when starting gulp, that the tag "includeData" is not recognized.
There is of course something missing but I have no idea what it is and I also did not find anything useful when searching the internet.
Hopefully someone is already using the includeData plugin sucessfully in his build process and can tell me what I have to change in the configuration.
Thank you very much in advance for any help!
best regards,
Thomas
At first you must check that extension installed
// test.json
{"name": "Bill"}
// your-app.js
...
includeData.install(env);
var res = res.renderString('{% includeData "test.json" %} {{name}}');
console.log(res); // Bill
This extension don't work on Node 5.x, because require destructuring assignment (see node_modules\nunjucks-includeData\index.js, line 78). Perhaps, you must update your Node.

Inject git branch name into HTML page

I work on an ASP.NET MVC web project, and we're developing several features concurrently. Each feature is on its own branch, and to test the site we publish it to a staging area.
However, after it's published I often forget from which branch we published.
Is there any way to inject the git branch name into the HTML somewhere, so the page will display <span>feature/coolNewFeature1</span> or <span>develop</span> as a reminder for which codebase is currently on the staging area?
Go to Project Properties and add a "pre-build event command line" script like:
git.exe rev-parse --abbrev-ref HEAD > "$(ProjectDir)\Resources\BuildInfo.txt"
Build the project, mark the "BuildInfo.txt" file as an Embedded Resource
In your footer cshtml, add code like:
#{
var buildInfo = Cache["buildInfo"];
if (buildInfo == null)
{
using (var r = new StreamReader(typeof(HomeController).Assembly
.GetManifestResourceStream("My.Module.Web.Resources.BuildInfo.txt")))
{
buildInfo = Cache["buildInfo"] = r.ReadToEnd();
}
}
}
#buildInfo
I am not super comfortable with ASP .NET but I can think of the following sequence of steps (I assume that you will select a git branch, compile and then deploy - and there is a script that possibly is automating this):
Create a small Javascript file (e.g. version.js) that declares
var version_branch = "<your-branch>";
Run a shell script (or it's equivalent on your platform)
$ t=$(git branch | grep "*" | cut -d' ' -f2) && echo "var version = '"$t"';" > /path/to/js/file
Include this in the Javascript files you are serving - like you might be doing for other Javascript. Remember to include a <script> tag for this file on your main template page.
When the page loads you can use jquery to inject this text in the footer as the accepted answer on this question suggests - Using CSS to insert text.
Hope this helps!

Polymer - url rooting after deployment to subdirectory

Ive created a basic Polymer app from the starter kit (via Yeoman). I've today deployed it to the 'sandbox' on my domain and am getting a strange routing issue. The app is essentially a feed reader.
View app here
When I first visit the app I'm given a blank page whereas locally I'm taken straight to the feed. When clicking on 'News Feed' I'm then taken to the feed as expected.
I've added a route for the path of the domain structure as below but this did not fix it.
You can view the full code of the project here.
routing.html
page('/', function () {
app.route = 'home';
});
page('http://purelywebdesign.co.uk/sandbox/f1feedreader/', function () {
app.route = 'home';
});
I've also tried:
page('/sandbox/f1feedreader/', function () {
app.route = 'home';
});
Any help much appreciated.
Page.js allows you to configure the base path:
page.base('/sandbox/f1feedreader/');
or just use window.location if you don't want to tie is to that specific deployment.
page.base(window.location.pathname);
This is an issue with the way the router page.js works. I assume you were testing with gulp serve (which creates a server and sets the web app base url of "/" to be localhost:3000/). The way you're currently setting your page.js routes is that it's looking exactly after the domain name and not at the "root" of the web directory.
In your case page.js is looking at everything after http://purelywebdesign.co.uk/ (meaning all your routes include should start from sandbox/f1feedreader instead of just /f1feedreader).
The documentation for page.js https://visionmedia.github.io/page.js/ says that it uses regular expressions so you could also update the strings.

How to have Express routing work with Angular routing with HTML5 style URLs?

I would like to make an AngularJS app with HTML5-style URLs (i.e. with no # fragment in the URL). Thus in the routing controller module of my Angular app I've got something like the following:
angular.module('app').config(['$routeProvider','$locationProvider',function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true)
...
}
$routeProvider
.when('/1/:param', /* do something */)
.when('/2/:param', /* do something else */)
.when('/3/:param', /* do something else again*/);
A number of working examples like AngularFun don't use HTML5 mode. For a request like http://localhost:3005/#/1/foo, it's clear that
the http://localhost:3005/ part is handled server-side / by Express. Express happily serves our Angular-enabled index.html
the /1/foo route is handled client-side by Angular's router
Say our server.coffee looks, as standard, something like the below (we serve the static dist directory that contains our compiled, minified Angular sources:
express = require 'express'
routes = require './routes'
dir = "#{__dirname}/dist" # sources live here
port = process.env.PORT ? process.argv.splice(2)[0] ? 3005
app = express()
app.configure ->
app.use express.logger 'dev'
app.use express.bodyParser()
app.use express.methodOverride()
app.use express.errorHandler()
app.use express.static dir # serve the dist directory
app.use app.router
routes app, dir # extra custom routes
If we do use HTML5 mode, our URL http://localhost:3005/#/1/foo becomes http://localhost:3005/1/foo (no more hash #). This time, the entire URL is intercepted by Express, and it gets confused because we don't define routes other than /.
What we would really like to say is that the latter part of the URL (/1/foo) should be 'delegated' to Angular for handling. How can we say this?
It appears that it does all work. I didn't do that work myself, however. I relied on this skeleton project:
https://github.com/thanh-nguyen/angular-express-seed-coffee
This allows you a certain degree of control over which paths are handled by the client and which by the server.