Skip to content

Instantly share code, notes, and snippets.

@dccampbell
Created March 19, 2016 03:12
Show Gist options
  • Save dccampbell/3f2c32adf49fc7a3f14c to your computer and use it in GitHub Desktop.
Save dccampbell/3f2c32adf49fc7a3f14c to your computer and use it in GitHub Desktop.
Functions for getting the page HTML, search/replacing domain strings, and saving text to a file. Tested in Chrome 49 via Tampermonkey.
window.addEventListener('load', function() {
var data = getPageHtml().replaceUrls('foo.com', 'bar.com');
var file = document.location.pathname.basename();
//saveToFile(data, file);
}, false);
/**
* Case-insensitive global string search/replace.
* The search includes copies of the url prefixed with: 'http:', 'https:', '//', and 'www.'
* @param {string} oldUrl - The url or domain string to be converted to regex and searched for.
* @param {string} newUrl - The string to replace any matches with.
* @return {string} the
*/
String.prototype.replaceUrls = function(oldUrl, newUrl) {
var domainStr = oldUrl.replace(/^\s*(https?:)?(\/\/)?(www\.)?/i, ''); // Strip scheme/slashes/www
var searchRegex = RegExp('(https?:)?(\/\/)?(www\.)?'+domainStr,'ig'); // Add optional scheme/slashes/www
return this.toString().replace(searchRegex, newUrl);
}
/** Save the given data to specified filename. */
function saveToFile(data, filename) {
var blob = new Blob([data], {type: "octet/stream"});
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.style = "display:none";
a.href = url;
a.download = filename ? filename : '';
document.body.appendChild(a);
a.click(); // Download!
a.remove();
window.URL.revokeObjectURL(url);
};
/** @return {string} the html tag and it's contents as an HTML string. */
function getPageHtml() {
return document.documentElement.outerHTML;
}
/** @return {string} the final path component */
String.prototype.basename = function() {
return this.toString().replace(/\/$/, '').split('/').pop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment