views:

1044

answers:

3

What's the best way to debug custom User Scripts (aka Greasemonkey) in Chrome? Is there a way to enable User Script tracking in the Developer Tools?

A: 

You could use a smaller script to actually inject your custom debug script into the page. At that point you will have the same access inside of developer tools as if it was actually included on the page.

Alex Sexton
LOL...that's essentially what I'm doing with my User Script and it's not working :)
+1  A: 

What kind of debugging do you want? Like Alex said, user scripts will be listed in the same context as debugging the page itself. If you go to the "scripts" tab in the developer tools, you'll see a bar with a dropdown which will allow you to select the appropriate javascript file you wish to debug. Such scripts should have urls that look like chrome-extension://<hash>/<script file>.js. Those scripts will also log to the console of the page they're embedded on.

Additionally, if you want to log in the same place for all pages, you can try building your script as a full chrome extension, using the user script as a content script. Then you can send a message from your content script to your background page and log there. For example, if this were your content script:

function log(text) {
  chrome.extension.sendRequest({'action' : 'log', 'text' : text}, function() {});
};
log("Content script loaded: " + window.location.href);

And this were your background page:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <script>
      function onRequest(request, sender, callback) {
        if (request.action && request.action == 'log') {
          console.log(request.text);
        }
      };

      chrome.extension.onRequest.addListener(onRequest);
    </script>
  </body>
</html>

You would see each load of the content script in the background page's log.

Arne Roomann-Kurrik
A: 

i user the following function in my scripts for cross-browser GM Api compatibility:

function testGM() {
var isGM = typeof GM_getValue != 'undefined' && typeof GM_getValue('a', 'b') != 'undefined';
if(typeof(unsafeWindow) == 'undefined') { unsafeWindow = window; }
if(!isGM) { log = function(msg) { try { unsafeWindow.console.log(msg); } catch(e) {} }; } else { log = GM_log; }
if(window.opera) log = opera.postError;
setValue = isGM ? GM_setValue : function (name, value) { return localStorage.setItem(name, value) };
getValue = isGM ? GM_getValue : function(name, def){ var s = localStorage.getItem(name); return s == null ? def : s };
}
testGM();

it's not mine. it's courtesy sizzemctwizzle @ userscripts.org

i only use log, getValue & setValue as of now, hence only these tree in that function.
You can also check out his guide.
Or you can checkout GIJoe's cross-browser GM Api too.

Vishal Shah