0

I'm making a debugging tool, part of it is a Chrome Extension, that is supposed to capture console.log calls and send the output through WebSocket.

How can I wrap console.log in content page so that it sends messages to background script? Following doesn't work:

function requestContent() {
    var code = [
        "var __console_log = window.console.log;",
        "function __sendSublime(msg) {",
            "chrome.extension.sendRequest(null, {",
                "method: 'send',",
                "data: msg",
            "});",
            "__console_log(msg);",
        "}",
        "window.console.log = __sendSublime;"].join('');
    chrome.tabs.executeScript(null, {code: code});
}

I'm calling this function from background script.

skrat
  • 5,518
  • 3
  • 32
  • 48
  • Chrome has built-in remote debugging functionality if you start it from the command-line with `--remote-debugging-port=...`; see here https://developers.google.com/chrome-developer-tools/docs/remote-debugging – Silviu-Marian Jun 03 '12 at 16:27
  • Duplicate of [Create shortcut to console.log()](http://stackoverflow.com/questions/5456709/create-shortcut-to-console-log), [alias to chrome console.log](http://stackoverflow.com/questions/5133649/alias-to-chrome-console-log), ... The issue is that the context of __console_log` is not `console`, but `window`, which is forbidden in Chrome. Use `var __console_log = console.log.bind(console);` to fix the issue. After applying the fix, open the console at the page in which the content script is executed. – Rob W Jun 07 '12 at 22:03
  • My previous comment addressed one issue. Another problem is that content scripts are executed in a separate scope, in which `window` is not equal to the page's `window`. To overcome this, read [this answer](http://stackoverflow.com/a/10053750/938089?accessing-global-object-from-content-script-in-chrome-extension). – Rob W Jun 07 '12 at 22:12

0 Answers0