4

Possible Duplicate:
Building a Chrome Extension - Inject code in a page using a Content script

Below is my initial attempt. First I created a test webpage:

- test.html -

<HTML>
<SCRIPT src="script.js"></SCRIPT>
</HTML>

- script.js -

function testFunction() {
  console("function successfully run!");
}

Then I created a very simple extension to see if I could run testFunction() from the content script:

- manifest.json -

{
  "name": "Function Test",
  "manifest_version": 2,
  "version": "1",
  "description": "An extension to experiment with running the javascript functions of the website being browsed.",
  "permissions": ["<all_urls>"],
  "content_scripts": [
    {
      "all_frames": true,
      "matches": ["<all_urls>"],
      "js": ["cs.js"],
      "run_at": "document_end"
    }
  ]
}

- cs.js -

scriptNodes = document.getElementsByTagName("script");
script = scriptNodes[0];
console.log(script.src);
script.testFunction();

Here is the console output:

file:///C:/.../script.js
Uncaught TypeError: Object #<HTMLScriptElement> has no method 'testFunction'

So, is it possible to run a function on a website you are browsing using a Chrome Extension?

Community
  • 1
  • 1
flea whale
  • 1,783
  • 3
  • 25
  • 38

1 Answers1

1

Seems to be impossible.

See #4658143 and http://code.google.com/chrome/extensions/content_scripts.html

However, content scripts have some limitations. They cannot:

  • Use chrome.* APIs (except for parts of chrome.extension)
  • Use variables or functions defined by their extension's pages
  • Use variables or functions defined by web pages or by other content scripts
Community
  • 1
  • 1
naeramarth7
  • 6,030
  • 1
  • 22
  • 26
  • Ooooooooh. Are you sure? Is there really no way? – flea whale Nov 05 '12 at 20:42
  • ... sorry, but that's what the official page says. :/ – naeramarth7 Nov 05 '12 at 20:50
  • -1 for saying "impossible". It's certainly possible (marked question as duplicate). – Rob W Nov 05 '12 at 20:59
  • I said "seems to be" not "it is". Nevermind! – naeramarth7 Nov 05 '12 at 21:00
  • @naeramarth7 A downvote is an encouragement to improve the answer (downvotes can be retracted). If you don't know how to correct the answer, then a deletion would be most suitable (so that future visitors don't get false information). – Rob W Nov 05 '12 at 22:16
  • 2
    @Rob W I'm not encouraged about the downvote. See, I refered to an already existing answer and the official developer's guide saying, that content scripts "cannot" do this. So the official word "cannot" makes me say, that it "seems impossible" for me in the first place - at least without exploiting. – naeramarth7 Nov 05 '12 at 22:22