0

I am using content script and background script. On tab loading a function is added to the window object. I will use this example: window.myFunc = function() {...};

I need to use myFunction from the background script, but because background is running on diffrent window - myFunc is not accessible

How can I use myFunc from the background script?

3
  • If it's in a different scope it won't be accessible, unless chrome gives you a way to access it. Commented Oct 13, 2016 at 14:33
  • I know that. This is why i am asking maybe it is possible with chrome Commented Oct 13, 2016 at 14:35
  • Have you checked the Chrome Extension API docs? Commented Oct 13, 2016 at 14:35

1 Answer 1

2

You can not use that exact function which is contained in your content script from your background script.

Your options are:

  1. Have the background script send a message to the content script which the content script interprets as a directive to run the appropriate function. The results can be returned to the background script in a message (which can be a direct response to the message directing the content script to run the function).
  2. Include an identical function with the background script. A single copy of the function's code could be contained in a separate file which is loaded as both a content script and as a background script. That would allow only one copy of the code to exist, but the actual functions called would be separate instances of the function each generated from the same code.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.