Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to inject JavaScript into the currently loaded page from the Chrome Developer Tools window?

I want to add a panel UI to the Chrome devtools window and display some information about the currently loaded page. To get the information, I want to inject some JavaScript code before the page is loaded, so that I can change the behavior of some methods.

I tested with the following code:

manifest.json

{
  "name": "Test Dev Panel",
  "version": "0.1",
  "description": "Extends the Developer Tools, replacing Array.toString() with a bogus one.",
  "devtools_page": "devtools.html",
  "manifest_version": 2,
  "permissions": ["<all_urls>"],
  "content_scripts": [{
    "matches": ["http://*/*"],
    "js": ["bogusarray.js"],
    "run_at": "document_start"
  }]
}

devtools.js

chrome.devtools.panels.create("Text Dev Panel",
                          "img/iconDev.png",
                          "panel.html");

bogusarray.js

Array.prototype.toString = function () {
    return 'Injected!';
  };

However, as the behavior of Array.toString() does not change, the JavaScript (bogusarray.js) seems never injected into the loaded pages. Is there any advice on this?

like image 785
kuu Avatar asked Dec 26 '22 08:12

kuu


1 Answers

Your injected script bogusarray.js does not script the page - it runs is a separate execution context and can only see the page's DOM. You could script the page via injecting a <script> tag into DOM from your content script, but it will still be too late to override functions like Array's prototype.

To achieve your goal, you should reload inspected page from within your DevTools extension using chrome.devtools.inspectedWindow.reload(). Just pass your overrides using injectedScript parameter into it.

like image 76
pavel.feldman Avatar answered Feb 13 '23 07:02

pavel.feldman