SHARE
TWEET

add asc shortcut keys v3

rccharles Jun 7th, 2019 197 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.    multiple command key shortcuts#4 7-Jun-2019
  3.  
  4.    Function:
  5.     command + s    to save the post.
  6.     control + command + h   Toggles between showing the underlying html and back to normal.
  7.                             Note: Apple filters the html.
  8.                             [ You should use this for view only.  Making changes is at your own risk. ]
  9.     control + command + p for pick picture
  10.     control + command + PageUp to decrease edit box size
  11.     control + command + PageDown to increase edit box size
  12.     control + command + t for quote
  13.  
  14.     If a reply page, make preferred community the default community
  15.    
  16.     Avoids use of jquery.  jquery is not working for me at this time.
  17.  
  18. Testing matrix:
  19.                     save  html  picture  PageUp  PageDown  Quote  Default  Help
  20.                           edit   pick                               com.    (?)
  21.  
  22. Create User Tip
  23.  
  24.  
  25. Edit User Tip                                                       --
  26.  
  27.  
  28. Create Discussion
  29.  
  30.  
  31. Edit Create                                                         --
  32.    Discussion
  33.  
  34. Reply to post                                                       --
  35.  
  36.  
  37. Edit Reply to                                                       --
  38.   post
  39.  
  40.  
  41.      
  42.     interesting
  43.       https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
  44.       https://discussions.apple.com/thread/250079673?page=1
  45.  
  46.     from Greasemonkey hacks: tips & Tools for Remixing the web with Firefox
  47.     by Julien Couvreur
  48.     Code from book with his gracious permission
  49.  
  50.     Javascript: The Definitive Guide 6th Edition
  51.  
  52.  
  53. https://stackoverflow.com/questions/2878983/capture-key-press-without-placing-an-input-element-on-the-page
  54. window.addEventListener('keydown', function (e) {
  55.   if (e.ctrlKey && e.keyCode == 90) {
  56.     // Ctrl + z pressed
  57.   }
  58. });
  59.  
  60. Assigns each level of a brace to a different color.
  61. http://www.balancebraces.com/
  62.  
  63. show utf character codes:
  64. https://mothereff.in/js-escapes#1%E6%BC%A2%E5%AD%97
  65.  
  66. getting and setting css variables
  67. https://davidwalsh.name/css-variables-javascript
  68.   How to initialize
  69.   :root {
  70.     --my-variable-name: #999999;
  71.   }
  72.  
  73.   getComputedStyle(document.documentElement)
  74.     .getPropertyValue('--my-variable-name'); // #999999
  75.  
  76.   document.documentElement.style
  77.     .setProperty('--my-variable-name', 'pink');
  78.    
  79. window.location.href returns the href (URL) of the current page.
  80.  
  81. What html characters do we need to escape?
  82.     &lt; (<)
  83.     &gt; (>)
  84.     &amp; (&)
  85.     &quot; double-quote (")
  86.    &apos; single quote (')
  87.  https://www.w3.org/International/questions/qa-escapes#use
  88.  
  89. Support for full regular expressions in include and exclude rules is also available.
  90. If the rule both starts and ends with a forward-slash (/) character,
  91. the contents inside those slashes are interpreted as a regular expression.
  92.  
  93. Types of url's we need to handle:
  94. https://discussions.apple.com/create/question?communityId=2206020
  95. https://discussions.apple.com/create/question    create tooltip > then another create discussion
  96.                                                 on screen suggests iphone
  97. https://discussions.apple.com/create/userTip?communityId=2206020
  98. https://discussions.apple.com/create/userTip     create tooltip > then another create tooltip
  99.                                                 on screen suggests iphone
  100. https://discussions.apple.com/thread/250075737
  101. https://discussions.apple.com/docs/DOC-250000368
  102.  
  103. */
  104.  
  105. /* eslint                                        */
  106. /* https://eslint.org/docs/rules/no-multi-spaces */
  107. /* Most of these rule adjustment don't work in   */
  108. /*   this browser :-(.                            */
  109. /* eslint "ignoreEOLComments": "off", "ignoreComments": "off" */
  110. // /*eslint no-caller: "error"*/
  111. // /* eslint no-multi-spaces: ["error", { ignoreEOLComments: true }] */
  112.  
  113. // ==UserScript==
  114. // @name        multiple command key shortcuts#6 6-Jun-2019
  115. // @namespace   bubo-bubo/gmscripts
  116. // @description Implement save and html edit shortcut.
  117. // @include     /https://discussions\.apple\.com/+thread/+.*/
  118. // @include     /https://discussions\.apple\.com/create/question.*/
  119. // @include     /https://discussions\.apple\.com/create/userTip.*/
  120. // @include     /https://discussions\.apple\.com/docs/.*/
  121. // @version     6-Jun-2019
  122. // @grant       none
  123. // ==/UserScript==
  124.  
  125.  
  126. var debug = 2; // 0 -- no debug
  127.               // 1 -- normal debug
  128.               // 2 -- intense debug
  129.               // 3 -- extremely intense
  130.  
  131. // Keeps tracks of what stage we are in our HTML edit.
  132. //  0 is not editing
  133. //  1 is editing.  Thereby displaying actually html.
  134. var trackHTMLEdit = false;
  135.  
  136. // Is event listner load deployed?
  137. var deployListnerLoad = false;
  138.  
  139. let aDate = new Date();
  140. console.log ("====> starting command key shortcuts, Version June 6th, 2019 on " + aDate + " <====");
  141.  
  142. // Setup once page is loaded.
  143. // This program monitors incoming keypress.  When a known key is observed, this program takes the
  144. // assigned action.
  145.  
  146. /* Most likely will be interactive.
  147.    The script will run after the main page is loaded, but before other resources
  148.    (images, style sheets, etc.) have loaded.
  149.    https://wiki.greasespot.net/Metadata_Block#.40run-at  */
  150. if (debug) console.log("document.readyState is " + document.readyState);
  151.  
  152. //  ready to roll? More stuff for later?
  153. if (document.readyState=="complete") {
  154.  console.log("rolling along")
  155.  // rolling along
  156.  pageLoadComplete()
  157. }
  158. else {
  159.  if (debug>=2) console.log('adding listeners')
  160.  // wait out page loading.
  161.  window.addEventListener("load",
  162.                          pageLoadComplete,
  163.                          true);
  164.  deployListnerLoad = true;
  165. }
  166. // register event listeners
  167. // nothing like starting at the end ;-)
  168. window.addEventListener('unload',
  169.        function(e)
  170.        {
  171.          if (debug) console.log('unloading.');
  172.          // may not be needed.  Wonder if that is bad?
  173.          if (deployListnerLoad) {
  174.            window.removeEventListener("load",
  175.                                       pageLoadComplete,
  176.                                       true);
  177.            deployListnerLoad = false;
  178.          }
  179.         if (deployedKeyScanner) {
  180.            window.removeEventListener("keypress",
  181.                                       processKey,
  182.                                       false);
  183.            deployedKeyScanner = false
  184.          }
  185.          // remove anonymous unload. [ Thus unload ]
  186.          window.removeEventListener(e.type,
  187.                                     arguments.callee,
  188.                                     true);
  189.        },
  190.        true);
  191.  
  192. // last set value is returned as return code.
  193. var done;
  194. done = 0;
  195.  
  196. // -----------------------------------------------------------------------------
  197. function pageLoadComplete() {
  198.  if (debug) console.log ("--> pageLoadComplete.  ");
  199.   // find how many reply buttons there are.  Not used for nothing.
  200.   if (debug>=2){
  201.     console.log("All page resources finished loading!")
  202.     const theNodes = document.querySelectorAll(
  203.       "button.button.button-black:not(.hidden):not(.button-checked)")
  204.     spew ("theNodes",theNodes)
  205.   }
  206.  
  207.   /* Let's get started. */
  208.   processPage()
  209.  
  210. } // end function pageLoadComplete
  211.  
  212. /* --------------------------------------------------------------------- */
  213. /* main line code */
  214. function processPage() {
  215.   if (debug) console.log ("--> processPage.  ");
  216.  
  217.   // See if this is a reply page which we will then click on preferred link to make default
  218.   // https://discussions.apple.com/create/question?communityId=2140020
  219.   // https://discussions.apple.com/create/userTip?communityId=2140020
  220.   // Skip:
  221.   // https://discussions.apple.com/profile/rccharles/subscriptions
  222.   const currentPage = window.location.href  // returns the href (URL) of the current page.
  223.   console.log ("currentPage is ", currentPage)
  224.   if ( currentPage.search(
  225.        /https:\/\/discussions.apple.com\/create\/question\?communityId=/
  226.      )>=0) {
  227.     // Default post from perferred community
  228.     let saveRevealIcon = document.querySelector(
  229.       'div.create-post-topic div.create-post-selection-list div.selector-item button.selector-choice')
  230.     if (debug>=2) console.log ("saveRevealIcon is ",saveRevealIcon)
  231.     if (saveRevealIcon) { /* clickAnchorTag(saveRevealIcon) */  }                                                  
  232.   }
  233.   else if ( currentPage.search(/https:\/\/discussions.apple.com\/create\/userTip\?communityId=/)>=0) {
  234.       let saveRevealIcon = document.querySelector(
  235.         'div.create-post-topic div.create-post-selection-list div.selector-item button.selector-choice')
  236.       if (debug>=2) console.log("saveRevealIcon is ",saveRevealIcon)
  237.       // make default community
  238.       if (saveRevealIcon) { /* clickAnchorTag(saveRevealIcon)*/ }
  239.     }
  240.  
  241.   /* Who knows, we might have to wait a bit */
  242.   /* <div class="editor-section"> */
  243.   //var theNode = document.querySelector("div.editor-section")
  244.   var theNode = document.querySelector("div#main-content")
  245.   console.log("theNode is ",theNode)
  246.   theNode.addEventListener("keypress",
  247.                            processKey,
  248.                            false);
  249.   deployedKeyScanner = true
  250.   if (debug) console.log ("done with processPage  ");
  251. } // end of processPage;
  252.  
  253. // -----------------------------------------;
  254. function processKey(event) {
  255.   if (debug) console.log("in processKey with event input event",event);
  256.   if (debug>=2) {
  257.     console.log("  event.altKey is " + event.altKey);
  258.     console.log("  event.ctrlKey is " + event.ctrlKey);
  259.     console.log("  event.metaKey is " + event.metaKey);
  260.     console.log("  event.shiftKey is " + event.shiftKey);
  261.     console.log("  event.charCode is " + event.charCode + "  event.key is " + event.key);
  262.   } // end if debug;
  263.   // Is the editor present?  Editor is present when a save button is present.
  264.   let saveButtonPresent = document.querySelector(
  265.                 'div.editor-section:not(.hidden) button.button[data-action="submit-post"], section.create-post div.create-post-buttons button.button.create-post-button');
  266.   if (!saveButtonPresent) {
  267.     console.log(" Not in editor.  No save button present");
  268.     // Ignore the character.  Character will percolate up.
  269.     // ----> go back
  270.     return
  271.   }
  272.   // Check modifier keys;
  273.   /*
  274.     command + s for save post
  275.     control + command + h toggle for html viewing
  276.                           [ You should use this for view only.  Making changes is at your own risk. ]
  277.     control + command + p for pick picture
  278.     control + command + PageUp to decrease edit box size
  279.     control + command + PageDown to increase edit box size
  280.     control + command + t for quote
  281.   */
  282.   if (event.altKey) {
  283.     // skip;
  284.     if (debug>=2) console.log ("  skipping altKey! no actions assigned.");
  285.   }
  286.   else if (event.shiftKey) {
  287.     // skip;
  288.     if (debug>=2) console.log ("  skipping shiftKey! no actions assigned.");
  289.   }
  290.   // meta key is required for save, html edit, quote and select picture;
  291.   else if (event.metaKey) {
  292.     if (debug>=2) console.log ("  metaKey found!");
  293.     // control key is required for html edit, quote, select picture etc.
  294.     if (event.ctrlKey) {
  295.       if (debug>=2) console.log ("  ctrlKey found!");
  296.       // could be control + command + h for html edit;
  297.       if (event.charCode === 104) {
  298.         if (debug>=2) console.log ("  command + control + h!");
  299.         htmlEdit(event);
  300.       }
  301.       // could be control + command + p for pick picture;
  302.       else if (event.charCode === 112) {
  303.         if (debug>=2) console.log ("  command + control + p!");
  304.         findPicture(event);
  305.         if (debug>=2) console.log ("  processed image");
  306.       }
  307.       // could be control + command + PageUp to decrease edit box size;
  308.       else if (event.key === "PageUp") {
  309.         if (debug>=2) console.log ("  command + control + PageUp!");
  310.         changeEditBoxSize(event,-100);
  311.         if (debug>=2) console.log ("  processed PageUp");
  312.       }
  313.        // could be control + command + PageDown to increase edit box size;
  314.       else if (event.key === "PageDown" ) {
  315.         if (debug>=2) console.log ("  command + control + PageDown!");
  316.         changeEditBoxSize(event,100);
  317.         if (debug>=2) console.log ("  processed PageDown");
  318.       }
  319.       // could be control + command + t to input a quote
  320.       else if (event.key === "t" ) {
  321.         if (debug>=2) console.log ("  command + control + t!");
  322.         makeQuote(event);
  323.         if (debug>=2) console.log ("  processed quote");
  324.       }
  325.     } // end of ctrlKey;
  326.     else {
  327.       if (debug>=2) console.log ("  processing metaKey!");
  328.       // could be command + s for save post
  329.       if (event.charCode === 115 ){
  330.         if (debug>=2) console.log ("  found command + s!");
  331.         // <div class="editor-section hidden">;
  332.         //   ... clipped ...
  333.         // <button class="button" data-action="submit-post">Post</button>
  334.         // same for repy and edit.
  335.         // div.editor-section
  336.         // let saveButton = document.querySelector('button.button[data-action="submit-post"]')
  337.         // noticed after reply, reminants are left hidden :-(. So, avoid hidden.;
  338.         let saveButton = document.querySelector(
  339.                 'div.editor-section:not(.hidden) button.button[data-action="submit-post"], section.create-post div.create-post-buttons button.button.create-post-button');
  340.         if (debug>=2) console.log ("saveButton is ",saveButton);
  341.         if (saveButton) {
  342.           clickAnchorTag(saveButton);
  343.           //  we will take control of command+s, so don't pass up to other event handlers.;
  344.           event.preventDefault();
  345.         }
  346.         else {
  347.           if (debug) console.log("We have no reply to save; bubble up.");
  348.         }
  349.       } // 115 or s;
  350.     } // end of else not control key;
  351.   } // metaKey;
  352.   //GetDescriptionFor(e,"  ");
  353.   if (debug>=1) console.log("  done with processKey");
  354. } // end of processKey;
  355.  
  356. /* --------------------------------------------------------------------- */
  357. function htmlEdit(event)
  358. {
  359.   /*
  360.       This html is for the reply and edit reply.  There is a slightly different format for
  361.       a new post and a user tip.
  362.       <div class="editor-section">
  363.         <div id="editor-placeholder" ... >
  364.           <div class="editor ql-container" ... >
  365.             <div class="ql-editor"
  366.               data-gramm="false"
  367.               data-placeholder="Tell us what’s on your mind."
  368.               contenteditable="true">
  369.   */
  370.   // find the editor section.
  371.   // Reply and Edit Reply catch first selector.
  372.   // Create new post and new user tip catch on second selector.
  373.   let saveTextNode = document.querySelector(
  374.     'div.editor-section:not(.hidden) div#editor-placeholder div.ql-editor, section.create-post div.editor.ql-container div.ql-editor')
  375.   if (debug>=2) console.log("saveTextNode is ",saveTextNode)
  376.   // is the user really doing an edit?
  377.   if (saveTextNode) {
  378.     // should we begin the HTML edit?
  379.     if (trackHTMLEdit===false) {
  380.       // request to edit.
  381.       let savedInnerHTML = saveTextNode.innerHTML
  382.  
  383.       displayHexString(savedInnerHTML,"    ")
  384.  
  385.       if (debug>=2) console.log("savedInnerHTML is ",savedInnerHTML)
  386.       // Convert display to HTML
  387.       // amazing.
  388.       // https://stackoverflow.com/questions/6234773/can-i-escape-html-special-chars-in-javascript
  389.       saveTextNode.innerText = savedInnerHTML
  390.       // toggle
  391.       trackHTMLEdit = true
  392.       //  we will take control of control + command + h, so don't pass up
  393.       //    to other event handlers.
  394.       event.preventDefault()
  395.     }
  396.     else {
  397.       // end HTML edit.  Convert to regular text.
  398.       if (debug>=2) console.log("displaying html. Convert back. ")
  399.       // already doing HTML edit.
  400.       let displayedText=saveTextNode.innerText
  401.       if (debug>=2) console.log("displayedText is ",displayedText)
  402.       saveTextNode.innerHTML = displayedText
  403.       // toggle
  404.       trackHTMLEdit = false
  405.       //  we will take control of control + command + h, so don't pass up
  406.       //    to other event handlers.
  407.       event.preventDefault()
  408.     }
  409.   } // end doing an edit found "right" node
  410.   else {
  411.     if (debug) console.log("reply edit note not found.")
  412.   }
  413. } // end of function htmlEdit
  414.  
  415. /* --------------------------------------------------------------------- */
  416. function findPicture(event) {
  417.    if (debug>=1) console.log ("in findPicture")
  418.    var savePicture = document.querySelector
  419.    ('button.rte-button.rte-hl-bg-active[data-rte="image"][aria-label="Insert Image"]')
  420.     // ('div.toolbar div.row  section.buttons-group:not(.hide-mobile) button.rte-button.rte-hl-bg-active:first-child')
  421.    if (debug>=2) console.log ("savePicture is ",savePicture)
  422.    if (savePicture) {
  423.      clickAnchorTag(savePicture)
  424.      //  we will take control of command+s, so don't pass up to other event handlers.
  425.      event.preventDefault();
  426.    }
  427. } // end of findPicture
  428.  
  429. /* --------------------------------------------------------------------- */
  430. /*
  431. // Set multiple styles in a single statement
  432. elt.style.cssText = "color: blue; border: 1px solid black";
  433. // Or
  434. elt.setAttribute("style", "color:red; border: 1px solid blue;");
  435.  
  436. // Set specific style while leaving other inline style values untouched
  437. elt.style.color = "blue";
  438.  
  439. https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
  440.  
  441. */
  442. function changeEditBoxSize(event,changeSize) {
  443.   if (debug>=1) console.log ("in changeEditBoxSize")
  444.   // if we find a messed up style, continue on our merry way.
  445.   try {
  446.    var saveEdit = document.querySelector('div.editor.ql-container');
  447.    if (debug>=2) console.log ("saveEdit is ",saveEdit);
  448.    if (saveEdit) {
  449.      let allStyle = saveEdit.getAttribute("style")
  450.      if (debug>=2) console.log("allStyle are ",allStyle);
  451.      // Have we been through here before?
  452.      if ( allStyle.search(/!important;/)>=0) {
  453.        // been there done that
  454.        editorHeight=saveEdit.style.getPropertyValue('--editor-height');
  455.        console.log("editorHeight via html is ",editorHeight)      
  456.      }
  457.      else {
  458.        // need to take from composite style
  459.        editorHeight = window.getComputedStyle(saveEdit).getPropertyValue('--editor-height')
  460.        console.log("editorHeight via getComputedStyle is ",editorHeight)
  461.      }
  462.        
  463.      /* https://stackoverflow.com/questions/8811027/
  464.      get-elements-custom-css-properties-mystyle-using-javascript/36609605#36609605 */
  465.    
  466.      // fyi: returns an array
  467.      editorHeightNumber = editorHeight.split("px")
  468.      console.log("editorHeightNumber is ",editorHeightNumber)
  469.      let count = Number(editorHeightNumber[0])
  470.      count+=changeSize
  471.      if (count <= 100){ count = Math.abs(changeSize) }
  472.      console.log("count is ",count)
  473.      const injectionString = count.toString()+"px !important;"
  474.      console.log("injectionString is ",injectionString, "typeof injectionString is "
  475.                  + typeof injectionString)
  476.      console.log("saveEdit.attributes are now ",saveEdit.attributes);
  477.      console.log("~1~style is ",saveEdit.getAttribute("style"));
  478.      // Up cascade priority
  479.      // setting css variable, --editor-height, drops off second word, "!important;".  :-(.
  480.      editorHeightHTML=saveEdit.style.getPropertyValue('--editor-height');
  481.      console.log ("editorHeightHTML is ", editorHeightHTML)
  482.      const alteredString = allStyle.replace(editorHeightHTML,injectionString)  
  483.      console.log (" alteredString is ", alteredString)
  484.      saveEdit.style.cssText = alteredString
  485.      console.log("~2~style is ",saveEdit.getAttribute("style"));
  486.      
  487.      if (debug>=2) console.log ("eat character")
  488.      //  we will take control of command+s, so don't pass up to other event handlers.
  489.      event.preventDefault()
  490.    }  // end of if (saveEdit)
  491.    else {
  492.      console.log("\nCould not find edit box!!!\n")
  493.    }
  494.    if (debug>=2) console.log ("bye from changeEditBoxSize")
  495.  
  496.    //Object.keys(inputObj).forEach(e => console.log(`key=${e}  value=${inputObj[e]}`));
  497.   } // end of try
  498.   catch (err) {
  499.     console.log ("Don't understand style format.\"" + err.message + "\"" )
  500.   } // end catch
  501.  
  502. } // end function changeEditBoxSize
  503.  
  504. /* --------------------------------------------------------------------- */
  505. // Click on the quote icon.
  506. function makeQuote(event) {
  507.   if (debug>=1) console.log ("in makeQuote")
  508.   try {  
  509.       // Now, click on the quote icon
  510.      let saveQuoteIcon  = document.querySelector
  511.        ('button.rte-button.rte-hl-bg-active[data-rte="blockquote"][aria-label="Quote"]')
  512.       //let saveQuoteIcon = document.querySelector('div.toolbar div.row.sub-row div.sub-row-wrapper section.buttons-group button.rte-button.rte-hl-bg-active[data-rte="blockquote"]');
  513.       if (debug>=2) console.log ("saveQuoteIcon is ",saveQuoteIcon)
  514.       if (saveQuoteIcon) {
  515.         clickAnchorTag(saveQuoteIcon)
  516.         // Well, we quoted the stuff added to the input area.
  517.         // seems good enough to count as processed request.
  518.         // we will take control of control + command+t,
  519.         // so don't pass up to other event handlers.
  520.         event.preventDefault();
  521.  
  522.         // Finally, click on the close secondary icon line.  X
  523.         let saveQuitIcon = document.querySelector('div.toolbar div.row.sub-row button.rte-close-button');
  524.         if (debug>=2) console.log ("saveQuitIcon is ",saveQuitIcon)
  525.         if (saveQuitIcon) {
  526.           clickAnchorTag(saveQuitIcon)
  527.         } // end of saveQuitIcon
  528.         else {
  529.           console.log ("saveQuitIcon not found!!! ")
  530.         }
  531.       } // end of saveQuoteIcon
  532.   } // end of try
  533.   catch (err) {
  534.     console.log ("makeQuote got confused. \"" + err.message + "\"" )
  535.   } // end catch
  536. } // end of function makeQuote
  537.  
  538. /* --------------------------------------------------------------------- */
  539. function GetDescriptionFor(e,inDent)
  540. {
  541. if (debug>=2) {
  542.   console.log (inDent + "in GetDescriptionFor")
  543.   console.log (inDent + "e.keyCode is " + e.keyCode )
  544.   console.log (inDent + "e.keyCode in hex is " +toHexString(e.keyCode,inDent+"  ") )
  545. }
  546. var result, code;
  547. if ((e.charCode) && (e.keyCode==0))
  548. {
  549.  result = "charCode: " + e.charCode;
  550.  code = e.charCode;
  551. } else {
  552.  result = "keyCode: " + e.keyCode;
  553.  code = e.keyCode;
  554. }
  555.  
  556. if (code == 8) result += " BKSP"
  557. else if (code == 9) result += " TAB"
  558. else if (code == 46) result += " DEL"
  559. else if ((code >= 41) && (code <=126)) result += " '" + String.fromCharCode(code) + "'";
  560.  
  561. if (e.altKey) result += " alt";
  562. if (e.ctrlKey) result += " ctrl";
  563. if (e.metaKey) result += " meta";
  564. if (e.shiftKey) result += " shift";
  565. console.log (inDent + "result is " + result)
  566. return result;
  567. } // end of GetDescriptionFor
  568.  
  569. /* --------------------------------------------------------------------- */
  570. /* print out objects:
  571.   https://stackoverflow.com/questions/957537/how-can-i-display-a-javascript-object
  572.   https://code-maven.com/logging-javascript-objects
  573. */
  574. function spew (objName,inputObj) {
  575.   if (debug>=1) console.log ("starting spew")
  576.   if (debug>=2) {
  577.     console.log (objName + " is: ", inputObj)
  578.     console.log ("inputObj.length is " + inputObj.length)
  579.     console.log ("typeof inputObj is " + typeof inputObj)
  580.     //this will show object gandalf IN ALL BROWSERS!
  581.     console.log(JSON.stringify(inputObj));
  582.     //this will show object gandalf IN ALL BROWSERS! with beautiful indent
  583.     console.log(JSON.stringify(inputObj, null, 4));
  584.     console.log("keys",Object.keys(inputObj));
  585.     console.log("lenght is " + Object.keys(inputObj).length)
  586.     console.log(Object.values(inputObj));
  587.  
  588.     //There is also this new option if you're using ECMAScript 2016 or newer:
  589.     try {
  590.       Object.keys(inputObj).forEach(e => console.log(`key=${e}  value=${inputObj[e]}`));
  591.     }
  592.     catch (err) {
  593.       console.log (" You must need ECMAScript 2016 or newer \""+ err.message + "\"" )
  594.     } // end catch
  595.  
  596.   } // end of if debug printing code
  597.   if (debug>=1) console.log ("ending spew")
  598. } // end of function spew
  599.  
  600. // -----------------------------------------
  601. //  demo
  602. //  http://mothereff.in/js-escapes#1%E6%BC%A2%E5%AD%97
  603. //;
  604. function displayHexString(value,inDent) {
  605.   if (debug>=1) console.log("in function displayHexString");
  606.   var hexString = value.hexEncode();
  607.   if (debug>=2) console.log (inDent + "hexString is " + hexString);
  608.   if (hexString.length % 2) {
  609.     hexString = '0' + hexString;
  610.   }
  611.   const increment = 16;
  612.   var prefixNumber = 0;
  613.   var prefixNumberSpan = increment;
  614.  
  615.   // print groups of sixteen;
  616.   while( hexString.length > increment ) {
  617.     let prefixHex = prefixNumber.toString(increment);
  618.     if (prefixHex.length % 2) {
  619.       prefixHex = '0' + prefixHex;
  620.     } // end of if;
  621.     // Print out on console.;
  622.     // four hex digits per one printable.;
  623.     console.log(prefixHex + " " + hexString.substring(0,increment) + "  " +
  624.                 value.substring(prefixNumber/4,prefixNumberSpan/4)               );
  625.     hexString = hexString.substring(increment);
  626.     if (debug>=3) console.log( "hexString is "+ hexString);
  627.     prefixNumber += increment;
  628.     prefixNumberSpan += increment;
  629.     if (debug>=3) console.log("prefixNumber is "+ prefixNumber + " prefixNumberSpan is " + prefixNumberSpan);
  630.   } // end of while;
  631.  
  632.   if (debug>=3) console.log("done with groups of  " + increment);
  633.   if ( hexString.length ) {
  634.     let prefixHex = prefixNumber.toString(increment);
  635.     if (prefixHex.length % 2) {
  636.       prefixHex = '0' + prefixHex;
  637.     } // end of if
  638.     // Print out on console.
  639.     console.log(prefixHex + " " + hexString);
  640.   } // end of if;
  641.  
  642. } // end of toHexString;
  643.  
  644. /* --------------------------------------------------------------------- */
  645. /*
  646. https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
  647.  
  648. <!DOCTYPE HTML>
  649. <html>
  650.   <body style="font-weight:bold;">
  651.     <div style="color:red" id="myElement">..</div>
  652.   </body>
  653. </html>
  654.  
  655. The style property is not useful for completely learning about the styles applied on the element,
  656. since it represents only the CSS declarations set in the element's inline style attribute, not
  657. those that come from style rules elsewhere, such as style rules in the <head> section, or
  658. external style sheets. To get the values of all CSS properties for an element you should use
  659. Window.getComputedStyle() instead.
  660.  
  661. The output would be something like:
  662.  
  663. ...
  664. fontWeight = '' > 'bold'
  665. color = 'red' > 'rgb(255, 0, 0)'
  666. ...
  667.  
  668. Note the presence of the value "bold" for font-weight in the computed style and the absence
  669. of it in the element's style property
  670. */
  671. function printCombinedStyle(element) {
  672. //var element = document.getElementById("myElement");
  673. var out = "";
  674. var elementStyle = element.style;
  675. var computedStyle = window.getComputedStyle(element, null);
  676.  
  677. for (prop in elementStyle) {
  678.   if (elementStyle.hasOwnProperty(prop)) {
  679.     out += "  " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n";
  680.   }
  681. }
  682. console.log(out)
  683. } // end of function printCombinedStyle
  684.  
  685. /* --------------------------------------------------------------------- */
  686. // https://stackoverflow.com/questions/21647928/javascript-unicode-string-to-hex
  687. String.prototype.hexEncode = function(){
  688.     var hex, i;
  689.  
  690.     var result = "";
  691.     for (i=0; i<this.length; i++) {
  692.         hex = this.charCodeAt(i).toString(16);
  693.         result += ("000"+hex).slice(-4);
  694.     }
  695.  
  696.     return result
  697. }
  698. /* --------------------------------------------------------------------- */
  699. /* based on:
  700.      https://stackoverflow.com/questions/902713/how-do-i-programmatically-click-a-link-with-javascript
  701. */
  702. function clickAnchorTag(inputObj) {
  703.     if (debug>=1) console.log("in clickAnchorTag.\n inputObj is",inputObj)
  704.  
  705.     var event = document.createEvent('MouseEvent');
  706.     if (debug>=2) console.log ("proceeding to set new event")
  707.     event = new CustomEvent('click');
  708.     if (debug>=2) console.log ("clicking...")
  709.     inputObj.dispatchEvent(event);
  710. } // end of clickAnchorTag
  711.  
  712. /*
  713. Exception: Error while performing task "pretty-print": Error: Unexpected character '`' (529:53)
  714. [4]</pp.raise@resource://devtools/shared/acorn/acorn.js:940:13
  715. [13]</pp.getTokenFromCode@resource://devtools/shared/acorn/acorn.js:2785:3
  716. [13]</pp.readToken@resource://devtools/shared/acorn/acorn.js:2490:10
  717. [13]</pp.nextToken@resource://devtools/shared/acorn/acorn.js:2482:66
  718. [13]</pp.next@resource://devtools/shared/acorn/acorn.js:2431:3
  719. [13]</pp.getToken@resource://devtools/shared/acorn/acorn.js:2435:3
  720. prettyFast@resource://devtools/shared/pretty-fast/pretty-fast.js:778:15
  721. @resource://devtools/server/actors/pretty-print-worker.js:41:24
  722. createHandler/<@resource://devtools/shared/worker/helper.js:85:24
  723.  
  724. @resource://devtools/server/actors/pretty-print-worker.js:51:12
  725. createHandler/<@resource://devtools/shared/worker/helper.js:85:24
  726.  
  727. */
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top