Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kchenthilrajan/2ce577d9735388ba4e3e to your computer and use it in GitHub Desktop.
Save kchenthilrajan/2ce577d9735388ba4e3e to your computer and use it in GitHub Desktop.
//This is a handy DOM manipulation script which is helpful to do daily chores.
//The script can be imported into the chrome browsers js snippets and the functions can be accessed from the console.
//Load jQuery and fileSaver
var jq = document.createElement('script');
var fs = document.createElement('script');
var zip = document.createElement('script');
var worker = document.createElement('script');
var deflater = document.createElement('script');
var inflater = document.createElement('script');
//Load the CDN
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
fs.src = "https://cdn.rawgit.com/Teleborder/FileSaver.js/master/FileSaver.js";
deflater.src = "https://cdn.rawgit.com/gildas-lormeau/zip.js/master/WebContent/deflate.js";
inflater.src = "https://cdn.rawgit.com/gildas-lormeau/zip.js/master/WebContent/inflate.js";
worker.src = "https://cdn.rawgit.com/gildas-lormeau/zip.js/master/WebContent/z-worker.js";
zip.src = "https://cdn.rawgit.com/gildas-lormeau/zip.js/master/WebContent/zip.js";
//Attach the script tag to the current Page's DOM
document.getElementsByTagName('head')[0].appendChild(jq);
document.getElementsByTagName('head')[0].appendChild(fs);
document.getElementsByTagName('head')[0].appendChild(worker);
document.getElementsByTagName('head')[0].appendChild(zip);
document.getElementsByTagName('head')[0].appendChild(deflater);
document.getElementsByTagName('head')[0].appendChild(inflater);
//To Identify which tab is currently selected.
var tabSelected = document.getElementsByClassName('gwt-TabBarItem gwt-TabBarItem-selected')[1]
.getElementsByTagName('div')[0].textContent;
//Some utility functions
String.prototype.toUnderscore = function(){
var str = this.replace(/([A-Z])/g, function($1){return "_"+$1.toLowerCase();});
Object.keys(whitelistUnderscore).forEach(function (key) {
var re = new RegExp(key, "g");
str = str.replace(re,whitelistUnderscore[key]);
});
return str;
};
String.prototype.capitalizeFirstLetter = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
Array.prototype.clear = function() {
return this.splice(0,this.length);
};
// End Utility functions
// This function can be called from the console by passing the operations parameter.
function performOperations(str){
// var tableIds = ['inherited', 'overridden', 'local'];
var tableIds = ['local'];
var buffer = [];
var groupName = document.getElementById('gwt-debug-groupPage-groupName')?document.getElementById('gwt-debug-groupPage-groupName').innerText:'';
buffer.push('------------'+groupName+'-----------');
console.log('------------'+groupName+'-----------');
tableIds.forEach(function(tableId)
{
var tableMsg = '---------'+tableId+'---------------';
buffer.push(tableMsg);
console.log(tableMsg);
var mytable = document.getElementById("gwt-debug-signalList-table")? document.getElementById("gwt-debug-signalList-table"): document.getElementById("gwt-debug-variableList-table-"+tableId);
var iterTable = Array.prototype.slice.call(mytable.rows, 0);
iterTable.forEach(function(row){
/*var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('Click');
div.appendChild(txt);
row.appendChild(div);*/
if(row.cells[1]&&row.cells[1].innerText){
var signalsToOperate = row.cells[1].innerText.trim();
if($getScriptForVariables.length==0 || $getScriptForVariables.indexOf(signalsToOperate)!=-1){
if(str==='click'){
console.log(row.cells[1].getElementsByTagName('a')[0].click());
}
if(str==='json'){
buffer.push('{name:\''+row.cells[1].innerText.trim()
+'\',type:\''+row.cells[3].innerText.trim().toUpperCase()+'\'},');
}
if(str==='func'){
//var funcBody = (row.cells[4].innerText.trim()).replace(/([0-9]{1,2}\n|\n\.{3})/g,'');
var funcBody = row.cells[4].getElementsByClassName('CodeMirror')[0].CodeMirror.getValue();
console.log(funcBody);
buffer.push({name:row.cells[1].innerText.trim().toUnderscore()+'.js',
funcBlob:funcBody.trim()});
}
if(str==='findReplace'){
//var funcBody = (row.cells[4].innerText.trim()).replace(/([0-9]{1,2}\n|\n\.{3})/g,'');
var findReplaceFuncBody = row.cells[4].getElementsByClassName('CodeMirror')[0].CodeMirror.getValue();
findReplaceObj.forEach(function(each){
findReplaceFuncBody = findReplaceFuncBody.replace(new RegExp(each.find, 'g'),each.replace);
});
row.cells[4].getElementsByClassName('CodeMirror')[0]
.CodeMirror.setValue(findReplaceFuncBody);
}
if(str==='generate'){
var funcName = row.cells[1].innerText.trim();
var funcTreatmentGroup = row.cells[3].innerText.trim().toUpperCase();
var funcType = row.cells[2].innerText.trim().toUpperCase();
var funcBody = (row.cells[4].innerText.trim()).replace(/([0-9]{1,2}\n|\n\.{3})/g,'');
var perfContainer = GetPerfoceURLContainer(row.cells[4]);
funcBody = funcBody.replace(/recipient.adwords_asr\s&&\n/g,'');
console.log(funcBody);
if($getScriptForVariables.length==0 || $getScriptForVariables.indexOf(funcName)!=-1){
$allVariables.push({
name : funcName,
type : funcType,
treatmentGroup : funcTreatmentGroup,
body : funcBody ,
url : perfContainer.value
});
}
}
if(str==='insertPerforceURLs'){
var funcName = row.cells[1].innerText.trim();
var perfContainer = GetPerfoceURLContainer(row.cells[4]);
if(!perfContainer.value){
perfContainer.value = perforceUrls[funcName.trim()];
console.log(funcName.toLowerCase().trim());
}
}
if(str==='emptyPerforceURLs'){
var funcName = row.cells[1].innerText.trim();
var perfContainer = GetPerfoceURLContainer(row.cells[4]);
perfContainer.value = '';
}
}
else if(str==='printAll'){//Just print the variable names..
//console.log(row.cells[1].innerText.trim()+'\t'+row.cells[2].innerText.trim().toLowerCase().capitalizeFirstLetter());
console.log(row.cells[1].innerText.trim());
}
}
});
});
var blobArr = [];
var i=0;
buffer.forEach(function(each){
var contentBlob = new Blob([each.funcBlob], {type: "text/plain;charset=utf-8"});
contentBlob.name = each.name;
i++;
blobArr.push(contentBlob);
});
if(blobArr.length>0){
zipBlob(blobArr);
}
// var blob = new Blob([buffer.join('\n')], {type: "text/plain;charset=utf-8"});
// saveAs(blob, str+"_results.txt");
if(str==='generate')
console.log('All function contents are stored in $allVariables');
};
for (var waiting=0;waiting<900000;waiting++){
// waiting
}
//Templates
var templates = {
buildFileTemplate :
'js_library('+
'\nname = "$fileName",'+
'\nsrcs = ["$fileName.js"],'+
'\ndata = ["$fileName.js"],'+
'\n)'+
'\n'+
'\naxp_script_compile('+
'\nname = "$fileName_compile",'+
'\njs_deps = [":$fileName"],'+
'\n)',
buildTemplateSnippet:
'axp_script_test('+
'\nname = "$fileName_test",'+
'\njava_deps = ["//ads/crm/axp/protos/datalayer/sources:asr"],'+
'\nscripts = [":$fileName"],'+
'\ntest = "$fileName_test.js",'+
'\n)'
}
function getTemplateBuilder(template){
return {build : function(fileName){return template.replace(/\$fileName/g,fileName);}}
}
function applyTemplate(template,files){
var result = [];
var builder = getTemplateBuilder(template);
files.forEach(function(each){
result.push(builder.build(each));
});
console.log(result.join('\n'));
}
// ... give time for script to load, then type.
jQuery.noConflict();
//Generate Perforce Urls
function getUrls(){
return jQuery('.com-google-devtools-codereview-fe-client-ui-FileListTable_BinderImpl_GenCss_style-fileCell')
.toArray()
.map(function(each){
var link = each.innerText;
if(link.indexOf('.js')>0 && link.indexOf('_test.js')===-1){
var nameOriginal = link.substring(link.lastIndexOf('/')+1,link.indexOf('.js'));
var name = jQuery.camelCase(nameOriginal.replace(/_/g,'-'));
return {name : name, link : link};
}
});
};
function generateUrls(urls){
var perforceURLS = {};
urls.forEach(function(each){
if(each){
perforceURLS[each.name.toLowerCase()]=each.link;
}
});
var arr = [];
Object.keys(perforceURLS).forEach(function(each){
arr.push(each+':\''+perforceURLS[each].trim()+'\'');});
return arr.join(',\n');
}
//$allVariables.sort(function(a,b){if(a.name > b.name){return 1;} if(a.name < b.name){return -1;} return 0;});
var $allVariables = [];
var $getScriptForVariables = [];
var findReplaceObj = [{find : 'ASRUtilities\.accountMetricsSum' , replace: 'QPRDerived.campaignMetricsSum'},
{find : 'ASRUtilities\.accountMetricsRatio' , replace: 'QPRDerived.campaignMetricsRatio'}];
function openAll(){
var useNew = true;
var oldContainerName = 'gwt-debug-variableList-table';
var newContainerName = 'gwt-debug-variableList-table-local';
var containerName = useNew ? newContainerName : oldContainerName;
var container = document.getElementById(containerName)?
document.getElementById(containerName):
document.getElementById("gwt-debug-signalList-table");
if(!container){
console.log('Container Id not found');
return;
}
var myButtons = container.getElementsByTagName("button");
var trueArray = Array.prototype.slice.call(myButtons, 0);
trueArray.forEach(function(button){button.click();});
};
//
function zipBlob(files) {
writer = new zip.BlobWriter();
zip.workerScriptsPath = "/js/zip/";
zip.useWebWorkers = false;
zip.createWriter(new zip.BlobWriter("application/zip"), function(writer) {
var f = 0;
function nextFile(f) {
fblob = files[f];
writer.add(fblob.name+'', new zip.BlobReader(fblob), function() {
// callback
f++;
if (f < files.length) {
nextFile(f);
} else close();
});
}
function close() {
// close the writer
writer.close(function(blob) {
// save with FileSaver.js
saveAs(blob, "example.zip");
});
}
nextFile(f);
}, onerror);
};
/*
function addFiles(files) {
writer = new zip.BlobWriter();
zip.createWriter(writer, function(writer) {
zipWriter = writer;
for (var f = 0; f < files.length; f++) {
zipWriter.add(files[f].name,
new zip.BlobReader(files[f]), function() {});
}
});
}
function saveZip() {
zipWriter.close(function(blob) {
saveAs(blob, "Example.zip"); // uses FileSaver.js
document.getElementById("file-input").value = null; // reset input file list
zipWriter = null;
});
}
*/
function GetPerfoceURLContainer(container) {
var elm = {};
var elms = container.getElementsByTagName("*");
for (var i = 0; i < elms.length; i++) {
if (elms[i].id === 'gwt-debug-variableAssignment-scriptReference') {
elm = elms[i];
break;
}
}
return elm;
};
var perforceUrls = {
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment