0

I am making a simple Chrome extension which will change the prototype of the Date object. I want the flow to be like the following.

  • inject.js loads
  • inject.js runs and changes setHours on the Date prototype
  • The rest of the page will use the setHours that I have now defined

My inject.js:

Date.prototype.setHours = function () {
  alert();
};

My manifest.json:

{
  // ... 
  "content_scripts": [
    {
      "matches": ["*"],
      "js": ["inject.js"],
      "run_at": "document_start"
    }
  ]
}

Note that I use the run_at property to instruct the script to run before any JS is loaded on the page. This seems to work as I invoked debugger and the page did not load.

I understand this may be explicitly blocked as it seems like it could maybe be a security issue? Though I have not seen any mention of modifying the prototype chain being disallowed.

I am unfortunately getting Cannot read properties of undefined (reading 'prototype')

Help would be greatly appreciated!

Dara Java
  • 2,410
  • 3
  • 27
  • 52

1 Answers1

-1

You can't do that directly from inject.js due to security as you said. inject.js would have to write another script into the document e.g.

const dateScript = document.createElement('script');
dateScript.src = chrome.runtime.getURL('date-modifier.js');
(document.head || document.documentElement).prepend(dateScript);
Dominic
  • 62,658
  • 20
  • 139
  • 163
  • I have implemented this but I needed to change my manifest to run at `document_end`. It appends the script successfully, but it is not run before the original JS on the page is run. – Dara Java Apr 13 '22 at 23:45
  • Is there even any way for me to delay the code on the page? – Dara Java Apr 13 '22 at 23:50
  • Use inline code as shown in [Use a content script to access the page context variables and functions](https://stackoverflow.com/a/9517879) – wOxxOm Apr 14 '22 at 06:26