0

I have been going around in circles with this, so I would appreciate some help

This is what I want to achieve

  1. User presses my extension ison
  2. Popup appears with two buttons, 'run function a' and 'run function b'
  3. When they press a button it runs the function in my own js file, that I have injected.
  4. Function a for example, could be to count the number of elements of a certain type in the active tab

So, I can inject my js file on page load (this is in my contentscript.js)

var s = document.createElement('script');
s.src = chrome.extension.getURL('temp-file.js');
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);

This works, and I can see the js being excuted

But what I can do is to have a function run that is in temp-file.js

For example in the popup I have

chrome.tabs.executeScript(null, {code:"shows();"});

I get this: Uncaught ReferenceError: shows is not defined

If I enter shows(); into the console, it works as expected

I presume that the issue is all about the context. I tried various things in the popup.js page to also inject the file but nothing seemed to work

Is anyone able to point me in the right direction please

Thanks

Grant

mozman2
  • 911
  • 1
  • 8
  • 17

2 Answers2

1

I presume that the issue is all about the context.

You're right about it.

The file "temp-file.js" has been injected into host page, so it is now part of host page context. Extension can mess with it - since it is in different context.

Run a function from injected js

Solution:

Not sure about what you are trying to achieve. pick what suits you:

  1. Split injected file Code/functions you want to execute on a page - use them as contentscript. In this case split you "temp-file.js" - part extension has execute (becomes part of contentscript) and part host page has to execute(your code snippet).

  2. use custom event Use custom event - generate custom event in contenscript - listen for it injected script. custom event

Community
  • 1
  • 1
Amit G
  • 2,293
  • 3
  • 24
  • 44
  • Thanks for confirming, I appreciated it.Thanks Kousick Shanmugam Nagaraj as well, after a nights sleep the link you sent made some sense. I have a follow up questions which I will post as a new post as it isn't directly related to this. Thanks again – mozman2 Jun 17 '15 at 07:56
  • I don't get what you meant by 1, but 2 is a correct solution. – Xan Jun 19 '15 at 13:13
-1

Your question does not say what exactly you are trying to achieve.

This is what I understood. You want to execute a function on your contentscript.js from your popup.js.

If that is the case then you can call a method on contentscript from popup.js like mentioned here https://developer.chrome.com/extensions/messaging

  • You did misunderstand the question. This is already what mozman2 is doing - but the method is not in the context of the content script. This needs an additional step. – Xan Jun 19 '15 at 13:13