Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

How to Promote your Content by Creating and Sticking Index Page in Blogger


How to Add Related Posts Automatically in Blogger


How to Promote Posts Based On Labels And Recency in Blogger


User Scripts to Change Html5 Video Player Speed


The Goal

I Would like to change the speed of HTML5 video player at pan.baidu.com, so I can spend less time on the video and finish it sooner.

The Implementation

I found some user script at greasyfork for Chrome with tampermonkey extension

Based on these 2 script, I made the following simple user script that can change video speed to 1.5, 1.75, 2.0.

Other Ideas

  • Able to resume playback of a video at the point in time it was left.

JavaScript Tips and Tricks


Run the Code

  • Console at Chrome DevTools

IDE

Data Structures

Vargs and spread syntax

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Check undefined

JavaScript Window Location

iframe

CDATA in script tag
  • when the doc is parsed as xml: like in blogspot editor.
createElement
Create a TextNode and add new line
document.createElement(“script”)
document.write

JavaScript that executes after page load

  • document.addEventListener("DOMContentLoaded", function(){});
  • window.addEventListener("load", function(){});

Don’t Use window.onload

Timer

Misc

Online Tools

Building Chrome Extension to Find All On Sale Products in Google Express


The Problem
Google express does have a page to show on-sale products from one store, like this one https://www.google.com/express/u/0/search?oc=on_sale&m=9090995, but for unknown reason, it only lists a very small part of all on-sale products.

I like on-sale products, so I build one chrome extension that lists all on-sale products from one store.

How to Use
We go to one store, then run "Find on-sale products in Express" -> "Find in all pages", or choose one category(such as grocery), then choose "Find in all pages".

How it Works
In Google Express, when we go to the end of the page, it will automatically load more data in current page. So the extension continues to scroll to end of page until there is no more data to load, then remove all not on-sale products.

How to Build it We use extensionizr to create one chrome extension, then change the manifest.json as below:
{
  "name": "Find on-sales products in Express",
  "version": "0.0.1",
  "manifest_version": 2,
  "homepage_url": "http://lifelongprogrammer.blogspot.com",
  "default_locale": "en",
  "background": {
    "page": "src/bg/background.html",
    "persistent": true
  },
  "permissions": [
    "contextMenus",
    "tabs",
    "activeTab",    
    "https://www.google.com/express/*"
  ],
  "content_scripts": [
    {
      "matches": [
        "https://www.google.com/express/*",
      ],
      "js": [
        "src/inject/inject.js"
      ],
    }
  ]
}
background.js
We create context menu in background.js. When user clicks one content menu, it uses message passing to call function defined in content scripts.

Here we use "documentUrlPatterns":showForPages, to only create the context menus in google express websites.
'use strict';
var showForPages = ["https://www.google.com/express/*"];
function findOnSalesProducts(info, tab, pageCount) {
    console.log("pageCount: " + pageCount);
    chrome.tabs.query({
        "active": true,
        "currentWindow": true
    }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            "functiontoInvoke": "findOnSalesProducts",
            "pageCount":  pageCount
        });
    });
}

function findAllSales(info, tab) {
    chrome.tabs.query({
        "active": true,
        "currentWindow": true
    }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            "functiontoInvoke": "findAllSales"
        });
    });
}

chrome.contextMenus.create(
{
"title": "Find in all pages",
"contexts" : ["all"],
"documentUrlPatterns":showForPages,
"onclick": function(info, tab) {
    findAllSales(info, tab)
  }
});
createSeperatorMenu();

chrome.contextMenus.create(
{
"title": "Find in current page",
"contexts" : ["all"],
"documentUrlPatterns":showForPages,
"onclick": function(info, tab) {
    findOnSalesProducts(info, tab, 0)
  }
});

createSeperatorMenu();

var pageCounts = ["5", "10", "20", "40", "60"];
for (let pageCount of pageCounts) {
  chrome.contextMenus.create(
  {
  "title": "Find in next " + pageCount + " pages",
  "contexts" : ["all"],
  "documentUrlPatterns":showForPages,
  "onclick": function(info, tab) {
      findOnSalesProducts(info, tab, pageCount)
    }
  });
}

function createSeperatorMenu()
{
  chrome.contextMenus.create(
   {
     "title": "-------------------------------------",
     "contexts" : ["all"],
     "documentUrlPatterns":showForPages     
   }
  ); 
}
content_scripts.js
Main function is defined in content_scripts.js.
It uses setInterval to scroll to end of page multiple times, and use css selector to find not-on-sale products, and then remove them.
'use strict';
chrome.extension.onMessage.addListener(function (message, sender, callback) {
  console.log("message: " + JSON.stringify(message))
  if(message.functiontoInvoke =="findOnSalesProducts")
  {    
    findOnSalesProducts(message.pageCount);
  } else if(message.functiontoInvoke == "findAllSales")
  {
    findAllSales();
  }
  return;
});
function findOnSalesProducts(times)
{
  if(times == 0)
  {
    removeAllNonSales();
    return;
  }
  let timesRun = 0;
  var interval = setInterval(function(){
      timesRun += 1;
      if(timesRun > times){
          console.log("clearInterval and removeAllNonSales");
          clearInterval(interval);
          removeAllNonSales();
      }
      console.log("scroll")
      window.scrollTo(0,document.body.scrollHeight);
  }, 500); 
}

function findAllSales()
{
  let lastProductsCount = 0, currentProductsCount = 0;
  console.log(lastProductsCount +" last1, current: "+currentProductsCount );  
  var interval = setInterval(function(){
      currentProductsCount = getProductsCount();    
      console.log(lastProductsCount +" last2, current: "+currentProductsCount );  
      if(currentProductsCount == lastProductsCount){
          console.log("clearInterval and removeAllNonSales");
          clearInterval(interval);
          removeAllNonSales();
          return;
      }
      console.log("scroll")
      window.scrollTo(0,document.body.scrollHeight);
      lastProductsCount = currentProductsCount;
      console.log(lastProductsCount +" last3, current: "+currentProductsCount );
  }, 1500); 
}

function getProductsCount()
{
  return document.querySelectorAll("body div.contentArea>div.right ul>li").length;
}

function removeAllNonSales()
{
  var allProducts = document.querySelectorAll("body div.contentArea>div.right ul>li")
  Array.prototype.forEach.call( allProducts, function( node ) {
      if(node.querySelectorAll("span.priceSale").length==0)
      {
        node.parentNode.removeChild( node );    
      }    
  });
}
Resources
Chrome Extension Overview

Creating Tampermonkey User Script in Chrome


Scenario
In some cases, we want to change our frequently-visited website a bit: such as add some shortcut key: click >(right arrow) to go to next page, click <(left arrow) to go previous page in current web site.

We can create chrome extension, but it's overkill in this case. 

Tampermonkey
Chrome partially supports Greasemonkey, but doesn't support @require, @resource, unsafeWindow, GM_registerMenuCommand, GM_setValue, or GM_getValue.

Luckily, Tampermonkey fixes this issue: it is fully compatible to Greasemonkey, including GM_registerMenuCommand, GM_xmlhttpRequest with cross domain support and access to the unsafeWindow object. 

We can install tampermonkey from webstore. Then use its dashboard to create(add) new user scripts locally.

We can create one simple Greasemonkey user script to do it, or install exsiting user scripts from 
https://greasyfork.org/
http://userscripts-mirror.org/
https://openuserjs.org/

Examples
EDX helper
When watch open source courses in EDX, I would like to add the following shortcut keys:
>(right arrow): go to next page, <(left arrow) to go to previous page, t to play/pause the video, m to toggle full screen.
Also I want to auto play the video.
// ==UserScript==
// @name       edx helper
// @namespace  lifelongprogrammer.blogspot.com
// @require     https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
// @version    1.0
// @description  some keybindings for edx: next, previous, play/pause
// @match      https://courses.edx.org/courses/*
// @copyright  2014+, Jeffery Yuan original author: Andrea Bisognin
// ==/UserScript==

this.$ = this.jQuery = jQuery.noConflict(true);
$(document).ready(function () {
 // auto play
 console.log("edx helper");
 setTimeout(function () {
  console.log("edx helper auto player");
  unsafeWindow.$("section.video-controls a[class='video_control play']").click();
 }, 2000);
 jQuery(document).keydown(function (e) {
  console.log("edx helper; key: " + e.keyCode);
  if (e.keyCode == 39) { //->
   unsafeWindow.$("div.sequence-nav > button.sequence-nav-button.button-next").click();
  }
  if (e.keyCode == 37) { // <-
   unsafeWindow.$("div.sequence-nav > button.sequence-nav-button.button-previous").click();
  }
  if (e.keyCode == 84 || e.keyCode == 116) { //t
   unsafeWindow.$("section.video-controls > div:nth-child(2) > ul > li:nth-child(1) > a").click();
  }
  if (e.keyCode == 67 || e.keyCode == 99) { //c
   unsafeWindow.$("div.lang.menu-container > a").click();
  }
  if (e.keyCode == 77 || e.keyCode == 109) { //m
   unsafeWindow.$("a.add-fullscreen").click();
  }

 });
});


Safaribooksonline Helper
Similarly, when watch videos on Safaribooksonline, I want to add >(right arrow): go to next page, <(left arrow) to go to previous page, f to open in full mode where we can still use left, right arrow keys.
// ==UserScript==
// @name       safaribooksonline helper
// @namespace  lifelongprogrammer.blogspot.com
// @require     https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
// @version    1.0
// @description  some keybindings for safaribooksonline: next, previous
// @match      http://techbus.safaribooksonline.com/*
// @copyright  2015+, Jeffery Yuan, https://github.com/private-face/jquery.fullscreen
// ==/UserScript==

function d(b){var c,a;if(!this.length)return this;c=this[0];c.ownerDocument?a=c.ownerDocument:(a=c,c=a.documentElement);if(null==b){if(!a.cancelFullScreen&&!a.webkitCancelFullScreen&&!a.mozCancelFullScreen)return null;b=!!a.fullScreen||!!a.webkitIsFullScreen||!!a.mozFullScreen;return!b?b:a.fullScreenElement||a.webkitCurrentFullScreenElement||a.mozFullScreenElement||b}b?(b=c.requestFullScreen||c.webkitRequestFullScreen||c.mozRequestFullScreen)&&b.call(c,Element.ALLOW_KEYBOARD_INPUT):(b=a.cancelFullScreen||
a.webkitCancelFullScreen||a.mozCancelFullScreen)&&b.call(a);return this}jQuery.fn.fullScreen=d;jQuery.fn.toggleFullScreen=function(){return d.call(this,!d.call(this))};var e,f,g;e=document;e.webkitCancelFullScreen?(f="webkitfullscreenchange",g="webkitfullscreenerror"):e.mozCancelFullScreen?(f="mozfullscreenchange",g="mozfullscreenerror"):(f="fullscreenchange",g="fullscreenerror");jQuery(document).bind(f,function(){jQuery(document).trigger(new jQuery.Event("fullscreenchange"))});
jQuery(document).bind(g,function(){jQuery(document).trigger(new jQuery.Event("fullscreenerror"))});
this.$ = this.jQuery = jQuery.noConflict(true);
// https://github.com/private-face/jquery.fullscreen
$(document).ready(function () {
 // auto play
 console.log("safaribooksonline helper");
 jQuery(document).keydown(function (e) {
  console.log("safaribooksonline helper; key: " + e.keyCode);
  if (e.keyCode == 39) { //->
   unsafeWindow.$("#bcv_next").click();
   //$('#nana').fullScreen(true)   
  }
  if (e.keyCode == 37) { // <-
  console.log("i am called 26"); 
   unsafeWindow.$("#bcv_previous").click();
  }
  else if (e.keyCode == 70 || e.keyCode == 102) { //f
   $('div.brightcove_video').fullScreen(true)
  }
 });
});

Resources
Userscripts.org down for good? Here are alternatives

Practice: Using JSZip to Download Current Week's Images in Blogger


The Task
There is a blogger: its main content is pictures and photos, client wants to allow users to download today, this week and this month's pictures.

The Solution
The basic idea is to send a request to Blogger feed url, parse its json response to get all image links, then use JSZip and JQuery Deferred pattern to download all remote images.
Using GAE to Serve JavaScript Files
After download JSZip and JSZip-Utils, we need put them somewhere, so the blogger can load them. So we create one GAE application, and put them in the webapp/js/jszip folders.

We only want to load these scripts if the pageType is item: mean current page is a post page. So we add the following code under <b:includable id='post' var='post'>:

<b:includable id='post' var='post'>
<b:if cond='data:blog.pageType == "item"'>
<script src='//youapp.appspot.com/js/jszip/jszip.min.js'/>
<script src='//youapp.appspot.com/js/jszip/jszip-utils.min.js'/>
<script src='//youapp.appspot.com/js/jszip/FileSaver.js'/>
</b:if>

Add Download Links to Item Page
<div class='blog-pager' id='blog-pager'>
 <b:if cond='data:blog.pageType == "item"'>
  <div class='blog-pager' id='blog-pager'>
     <div id='blog-pager-newer-link'>
    <a class='blog-pager-newer-link' href='' id='downloadToday'>Download Today's Images</a>
   </div>

   <div id='blog-pager-older-link'>
    <a class='blog-pager-newer-link' href='' id='downloadMonth'>Download This Month's Images</a>
   </div>

  <div id='blog-pager-home-link'>
    <a class='blog-pager-newer-link' href='' id='downloadWeek'>Download This Week's Images</a>
  </div>

  </div>
 </b:if>
...
</div>
The Complete JavaScript Code
Using Blogger Feeds URL to Get Post in Range
Using JSZip and JQuery Deferred Pattern to Download Multiple Remote Images
<b:includable id='post' var='post'>
<b:if cond='data:blog.pageType == "item"'>
<script src='//lifelongprogrammertools.appspot.com/js/jszip/jszip.min.js'/>
<script src='//lifelongprogrammertools.appspot.com/js/jszip/jszip-utils.min.js'/>
<script src='//lifelongprogrammertools.appspot.com/js/jszip/FileSaver.js'/>
<script>
  var dateHeader= '<data:post.dateHeader/>';
  var parts = dateHeader.split('-');
  var postDate = new Date(parts[0], parts[1]-1, parts[2]);
  console.log("postDate:" + postDate);  
//<![CDATA[

$(function($) {
  if(JSZip.support.blob) {
   $("#downloadToday").click(function (e) {
   getTodayAllImages(dateHeader);
         e.preventDefault();
         return false;
   });
   $("#downloadWeek").click(function (e) {
   getWeekAllImages(postDate);
         e.preventDefault();
         return false;
   });
   $("#downloadMonth").click(function (e) {
   getMonthAllImages(postDate);
         e.preventDefault();
         return false;
   });

  }
});

function addToZip(zip, link, postUrl, i) {
var deferred = $.Deferred();

 JSZipUtils.getBinaryContent(link, function (err, data) {
    if(err) {
      alert("Problem happened when download image from " + postUrl + ", img link: " + link);
      console.error("Problem happened when download image from " + postUrl + ", img link: " + link);
      deferred.resolve(zip); // ignore this error: just logging
      // deferred.reject(zip);
    } else {
      zip.file("picture"+i+".jpg", data, {binary:true});
      deferred.resolve(zip);
    }
 });
return deferred;
}

function parseImagesRsp(root){
    var feed = root.feed;
  var parser = new DOMParser();  
  var zip = new JSZip();
  var deferreds = [];
  for(var i=0; i<feed.entry.length; i++)
  {
   var e=feed.entry[i];
   var doc = parser.parseFromString(e.content.$t, "text/html");
   var img = doc.querySelector("img");
   var pageUrl = e.link[2].href;
   if(!img)
   {       
     console.error("No img tag in " + pageUrl);  
   }
   else{
     var imgLink = img.src;
     console.log("img link: " + imgLink);
     deferreds.push( addToZip(zip, imgLink, pageUrl, i) );
   }
  }

$.when.apply(window, deferreds).done(generateZip);
}
function generateZip(zip)
{
 var content = zip.generate({type:"blob"});
 // see FileSaver.js
 saveAs(content, "downloadImages.zip");
}
function doDownload(startDate, endDate){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '/feeds/posts/default?published-min=' + startDate + '&published-max='+endDate+'&alt=json-in-script&max-results=1000&callback=parseImagesRsp';
    document.getElementsByTagName('head')[0].appendChild(script);
}
function getTodayAllImages(dateStr){
 var startDate = dateStr + "T00:00:01", endDate = dateStr + "T23:59:59";
    console.log("Download images from " + startDate + " to " + endDate);
    doDownload(startDate, endDate);
    return false;
}
function getMonthAllImages(dateObj){
 var startDate = yymmdd(getFirstDayOfCurrentMonth(dateObj)) + "T00:00:01", endDate = yymmdd(getLastDayOfCurrentMonth(dateObj))  + "T23:59:59";
    doDownload(startDate, endDate);
    return false;
}
function getWeekAllImages(dateObj){
 var startDate = yymmdd(getMondayOfCurrentWeek(dateObj)) + "T00:00:01", endDate = yymmdd(getSundayOfCurrentWeek(dateObj))  + "T23:59:59";
    doDownload(startDate, endDate);
    return false;
}
function yymmdd(dataObj){
  var month = (dataObj.getMonth()+1);
  var monthStr = month<10? ('0' + month): month;
  var dateStr = dataObj.getDate()< 10? ('0' + dataObj.getDate()): dataObj.getDate();
  return dataObj.getFullYear() + "-" + monthStr + "-" + dateStr;
}
function getMondayOfCurrentWeek(d)
{
    var day = d.getDay();
    return new Date(d.getFullYear(), d.getMonth(), d.getDate()-day + (day == 0 ? -6:1));
}
function getSundayOfCurrentWeek(d)
{
    var day = d.getDay();
    return new Date(d.getFullYear(), d.getMonth(), d.getDate()-day + (day == 0 ? 0:7));
}
function getFirstDayOfCurrentMonth(d){
  return new Date(d.getFullYear(), d.getMonth(), 1);
}
function getLastDayOfCurrentMonth(d){
  return new Date(d.getFullYear(), d.getMonth()+1, 0);
}
//]]>
</script>
</b:if>

Blogger: Get Url of First Post


The Solution
Edit the blogger's template to include the following javascript code:

<script>
function getFirstPostLink(){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '/feeds/posts/default?alt=json-in-script&max-results=1&callback=parseRsp';
    document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRsp(root){
    var feed = root.feed;
    var e0 = feed.entry[0];
    var firstPage = e0.link[2].href;
    // use the firstPage lin: window.location.href=firstPage;
}
getFirstPostLink();
</script>
Resources
Advanced Blogger Feeds Settings
Blogger Feed URLs

Practice: Using JSZip to Download Multiple Remote Images


Using JSZipUtils.getBinaryContent
JSZipUtils provides getBinaryContent to fetch a file from remote server like below:
// loading a file and add it in a zip file
JSZipUtils.getBinaryContent("path/to/picture.png", function (err, data) {
   if(err) {
      throw err; // or handle the error
   }
   var zip = new JSZip();
   zip.file("picture.png", data, {binary:true});
});
Using JQuery Deferred Pattern to Wait all Ajax Request Finished
We will loop all image urls, and call getBinaryContent to add the remote image into the dest zip file. But getBinaryContent is an async call, it will return immediately. We have to wait until al ajax request fished: either succeeded or failed.

We can use JQuery Deferred pattern: 

When loop al image urls, we will call addToZip: it calls JSZipUtils.getBinaryContent and return a Deferred object, which will be set as resolved when the ajax request finished. 
We put all Deferred objects into an array, then use jQuery.when().done(generateZip) to execute the callback generateZip when all ajax requests finished.
The generateZip will generate the zip and call saveAs in FileSaver.js.
The Complete Code
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'/>
<script src='/js/jszip/jszip.min.js'/>
<script src='/js/jszip/jszip-utils.min.js'/>
<script src='/js/jszip/FileSaver.js'/>
<script>
function downloadAllImages(imgLinks){
 var zip = new JSZip();
 var deferreds = [];
 for(var i=0; i<imgLinks.length; i++)
 {
  deferreds.push( addToZip(zip, imgLinks[i], i) );
 }
 $.when.apply(window, deferreds).done(generateZip);
}
function generateZip(zip)
{
 var content = zip.generate({type:"blob"});
 // see FileSaver.js
 saveAs(content, "downloadImages.zip");
}
function addToZip(zip, imgLink, i) {
  var deferred = $.Deferred();
  JSZipUtils.getBinaryContent(imgLink, function (err, data) {
    if(err) {
      alert("Problem happened when download img: " + imgLink);
      console.erro("Problem happened when download img: " + imgLink);
      deferred.resolve(zip); // ignore this error: just logging
      // deferred.reject(zip); // or we may fail the download
    } else {
      zip.file("picture"+i+".jpg", data, {binary:true});
      deferred.resolve(zip);
    }
 });
return deferred;
}
</script>
Resources
jQuery.Deferred is the most important client-side tool you have
Understanding JQuery.Deferred and Promise
How to use JSZip
JSZipUtils.getBinaryContent

Blogger: Get Post Publish Date in JavaScript


You may want to use value of Blogger's data tag inside javascript. 
For example to get the page type of current page, you may add the following code in the template:
<script>
var pageType = '<data:pageTitle/>';
</script>

To get the publish date of current post when page type is "item" (post page).
First in Layout tab, change the Blog Posts widget to include date header like below:

Then search <b:includable id='post' var='post'> in your blogger's template, add the following code below it:

<b:includable id='post' var='post'>
<b:if cond='data:blog.pageType == "item"'>
<script>
  var dateHeader= '<data:post.dateHeader/>';
  var parts = dateHeader.split('-');
 var postDate = new Date(parts[0], parts[1]-1, parts[2]);
</script>
</b:if>

If you don't want to show date header in post, then make it invisible by adding the following css in your blogger template:
<style>
  .date-header {display: none;}
</style>

To view a complete list of Blogger's data tags, check:
How to make a blogger template : data tags - part 1
How to make a blogger template : data tags - part 2

Using Javascript to Disallow IFramed and How to Hack it


Using Javascript to Disallow IFramed
By accident, I accessed http://www.webupd8.org/, which uses the following JavaScript to disallow other sites to put its webpages into iframe.

If you put it the follow iframe in webpage, it will open an alter dialog and redirect to its original site webpage.
<iframe src="http://www.webupd8.org/"></iframe>
How it's implemented
It compares the top window with self, if they are not same, then current page is put inside a frame.
The top property returns the topmost browser window of the current window. 
The self property returns the current window.

<script type='text/javascript'> 
// <![CDATA[
if ( top != self) {      
   top.location.replace(document.location);
   alert("iFrame not allowed; click OK to load this page without the iFrame.")
}
// ]]>
</script>
How to Hack It
But this protection can be easily bypassed and hacked.
In HTML5, the iframe has a new attribute sandbox to help safeguard your site from the embedded iframe. 
allow-same-origin - allows the iframe to access cookies and local storage from the parent, as if it came from the same domain.
allow-top-navigation - allows the iframe to navigate the parent to a different URL.
allow-forms - allows form submission
allow-scripts - allows JavaScript execution
allow-popups - allows the iframe to open new windows or tabs
allow-pointer-lock - allows pointer lock
so if we add sandbox="" or just sandbox in the iframe attribute, then brwoser will disallow javscript in the iframe to be executed.  Then the previous javascript protecttion would be voided.
<iframe allowtransparency="true" frameborder="0" sandbox="" scrolling="no" src="http://www.webupd8.org/" style="border: none; overflow: hidden;"></iframe>
Resources
Protect Your Website From Its Embedded Content With Iframes
HTML iframe sandbox Attribute

JavaScript: Get the First and Last day of Current Week and Month


Get the First and Last day of Current Week

The basic idea is to use getDate() and getDay(), and get the difference of current date and the first or last day of this week.

  • getDate() returns the day of the month (from 1 to 31) for the specified date.
  • getDay() returns the day of the week (from 0 to 6) for the specified date.
function getMondayOfCurrentWeek(d)
{
    var day = d.getDay();
    return new Date(d.getFullYear(), d.getMonth(), d.getDate() + (day == 0?-6:1)-day );
}
function getSundayOfCurrentWeek(d)
{
    var day = d.getDay();
    return new Date(d.getFullYear(), d.getMonth(), d.getDate() + (day == 0?0:7)-day );
}

Get the First and Last day of Current Month

function getFirstDayOfCurrentMonth(d){
  return new Date(d.getFullYear(), d.getMonth(), 1);
}
function getLastDayOfCurrentMonth(d){
  return new Date(d.getFullYear(), d.getMonth()+1, 0);
}

Get String in yyyy-mm-dd Format

function yymmdd(dataObj){
  var month = (dataObj.getMonth()+1);
  var monthStr = month<10? ('0' + month): month;
  var dateStr = dataObj.getDate()< 10? ('0' + dataObj.getDate()): dataObj.getDate();
  return dataObj.getFullYear() + "-" + monthStr + "-" + dateStr;
}

How to Hide Labels count < X from Label Widget in Blogger


JavaScript: Convert Relative Link in Selected Html to Absolute Path


In the previous post, we get the selected html, but usually we also need convert the relative link  to absolute path.
The Code

Tested in Chrome:
var thisPageUrl = stripQueryStringAndHashFromPath(window.location.href);

function stripQueryStringAndHashFromPath(url) {
 return url.split("?")[0].split("#")[0]; 
}

var hrefPattern = /href="([^"]*)"/;  
function changeToAbsoluteUrl(linkElement)
{
   var outerHTML = linkElement.outerHTML;
   var match= outerHTML.match(hrefPattern);
   if(match!=null)
   {
      var href= match[1];
      linkElement.href= thisPageUrl + href;
   }
}

function parseSelection() {
  var selection = window.getSelection();
  
  if(selection.rangeCount > 0)
  {   // please get source code of getSelectionHtml from 
      // http://lifelongprogrammer.blogspot.com/2014/05/javascript-get-selected-html-in-webpage.html
      var selectedHtml = getSelectionHtml(selection);
      var parser = new DOMParser()
      var selectedDoc = parser.parseFromString(selectedHtml, "text/html");      
      var elements = selectedDoc.getElementsByTagName("a");

      var arrayLength = elements.length;
      for (var i = 0; i < arrayLength; i++) {
       var element = elements[i];
       changeToAbsoluteUrl(element);
      }
      
      selectedHtml = selectedDoc.getElementsByTagName("body")[0].innerHTML;
      console.log("selectedHtml: " + selectedHtml);
  }   
}

parseSelection();

JavaScript: Get the Selected Html in Webpage


The Code
Tested in Chrome:
function getSelectionHtml(selection) {
  var range = selection.getRangeAt(0);
  
  var div = document.createElement('div');
  div.appendChild(range.cloneContents());
  var htmlText = div.innerHTML;
  return htmlText;
}

function parseSelection() {
  var selection = window.getSelection();
  
  if(selection.rangeCount > 0)
  {
      var selectedHtml = getSelectionHtml(selection);
      console.log("selectedHtml: " + selectedHtml);
  }   
}

parseSelection();

Using Chrome DevTools to Bring Default Context Menu: Enable Copy Text


The Problem
Sometimes site owners disable right-click context menu for some reason: to disallow copy text, or to protect better user experience such as Google Drive and Dropbox:  remove browser context menu and add customized context menu.

As web developer, or hackers, we use Chrome Devtools often, especially its "Inspect Element" function, so sometimes we want to remove this limitation: to bring back the browser default context menu.


Enable Copy - Chrome extension
Simple Solution that Works Most Time: document.oncontextmenu = null
or document.designMode = "on"
Site owner usually add javascript like below to disable context menu: <body oncontextmenu="return false;">
Or:
document.oncontextmenu = function() {
    return false;
};
In this case, we can just execute document.oncontextmenu = null in Chrome Devtools to remove the handler.

But sometimes, things are harder. Let's take a look at how to show default context menu in Google Drive as an example.

If this doesn't work you may run the following javascript code in devtools:
window.oncontextmenu=null;;
window.onmousedown=null;
window.onkeydown=null;
window.onclick=null;

document.oncontextmenu=null;
document.onmousedown=null;
document.onkeydown=null;
document.onclick=null;

document.onselectstart=null;
Re-enable Default Context Menu in Google Drive: by Changing Definition of hca function
To restore the default browser context menu in Google Drive, we first open Chrome Devtools(Using Ctrl+Shift+I), in the bottom panel, go to search tab, type "contextmenu".

It will find matches in js file: 2222407164-doclist_modularized_core.js


Clicking one match will bring you to the line, but this js file is minified, and ubale to read. SO click on the pretty button {}, this will format the js file to make it more readable.


Then search "contextmenu" again in the button search tab. Now it will show matches in the formatted js file. 


The following code seems interesting to us. e.Yqa prevent context menu default behaviour.
e.initialize = function(a) {
    b.listen(a, "contextmenu", this.Yqa);
};
e.Yqa = function(a) {
    a.shiftKey || (a.stopPropagation(), a.preventDefault(), pCa(this, a.clientX, a.clientY, a.target))
};
Let's add a breakpoint in the e.Yqa function, right click on Google Drive, now it stops at the Yqa function. This is great.

From the Call Stack view, we can see that e.Yqa function is called by function hca.
function hca(a, b) {
    var c = a.Gn, d = a.Xd || a.src;
    a.Ooa && Ze(a);
    return c.call(d, b)
}
hca is a global function, we can change its definition in the console to change its behavior.


Check the value of parameter a, and b. Found out when we right click in Google Drive, the value of a.type is "contextmenu".

So we can change hca like below: if a.type="contextmenu", do nothing, return directly.
function hca(a, b) {
   if( a.type == "contextmenu" ) return;
    var c = a.Gn, d = a.Xd || a.src;
    a.Ooa && Ze(a);
    return c.call(d, b)
}
So every time, we want to show Chrome's default context menu in Google Drive, run the previous js code in the console to change the definition of hca. Then right click on Google Drive, it will show default context menu.

Happy hacking!!!

Resource
Don’t Disable Right Click!

Using Chrome DevTools to Hack Client-Side Only Validation


Client-side validation can provide faster response and better user experience, and reduce server load. But relying client-side validation alone is a terrible idea.  

As user can easily bypass the validation, change value of javascript object using tools like Chrome DevTools or Firebug. We must always appropriate server-side validation as well.
Using Chrome DevTools to Hack it
One website limits the max value of one field, and I am wondering whether I can bypass the verification.
1. Found the pattern
I noticed that when I input invalid value, and go to next field, it will change the color of the field to red.
2. Beak on DOM Attributes Modifications 
So when the color of the field changes, I want Chrome to stop at that moment, so I can figure out how this website do the verification.

So I right click the input textbox, click "Inspect Element", this will open Chrome DevTools, and select the checked element in "Elements" tab. 
<input title="" class="input_field_" type="text" name="Memory" id="memory">
Right click it, and select "Break on..." -> "Attributes modifications".

This will cause Chrome pauses when attribute of this input textbox changes.
It would be better if Chrome DevTools allows us to stop when a particular attribute changes, in this case: class field. or even better to stop when a particular attribute changes to a particular value. But anyhow this works.
3. Reproduce It
Now input the invalid value, then trigger the event that will cause the client side validation. Usually this will happen when we focus leaves current field or we click next or submit.

This will cause Chrome stops execution, and switch to "Sources" tab and stops at the code that change 
4. Check the Call Stack
Now we can check the call stack. 
To make  javascript much easier to read, we can press the "Pretty print" button (marked with curly braces{}) from the bottom of the "Sources" tab.

Follow the call stack, I found it do verification like below:
function validateSteps(step) 
{
    var isStepValid = true;
  // omitted
    if (step == step_config) {
        return validateField('#memory', selectedPolicy.minMemory, selectedPolicy.maxMemory) &&...);
    }
    return isStepValid; // we can set a breakpoint value here to change isStepValid to true. 
}
The code compare the value from memory textbox with selectedPolicy.minMemory, selectedPolicy.maxMemory.
5. Hack it
Now there are several ways to hack it: we can step into validateField method and change return value.
The simpler way is to directly modify the object selectedPolicy, change maxMemory to a much bigger value. We go to the "Console" tab, and type selectedPolicy.maxMemory, this will print current value, it's 4. We can type selectedPolicy.maxMemory=100.

Now unclick all breakpoints, and press resume, and submit the form. It works, this site doesn't check the value in server side at all.

Later if I want to so the same trick: bypass the verification, I can go to "Console" tab directly, and type selectedPolicy.maxMemory=100.

In Console tab, we can do many things, run any valid javascript code in current scope.
We can check windows object, and detect any custom properties and functions.

Happy Hacking!!!
Resources
Tips And Tricks

Labels

ANT (6) Algorithm (69) Algorithm Series (35) Android (7) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) JSON (7) Java (186) JavaScript (27) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) adsense (5) bat (8) regex (5) xml (5)