wezternator
wezternator

Reputation: 167

Injecting JS into local Extension file (in new tab)

I spawn a new tab using chrome.tabs.create() that tab goes to a page within the chrome extension. I then want to use chrome.tabs.executeScript() to inject a JavaScript file into the new tab (enter_content.js). However when I do this I am greeted with the error

Error during tabs.executeScript: Cannot access contents of url "chrome-extension://adcfbbpepclgchodmdfbijpjhkgcamcg/enter.html". Extension manifest must request permission to access this host.

My manifest looks like this

{
    "manifest_version": 2,

    "name": "myExtension",
    "version": "1.0",

    "permissions": [
        "contextMenus",
        "tabs",
        "*://*/*"
    ],

    "background": {
        "scripts": ["background.js"]
    },

    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["generic_content.js"],
        "all_frames": true,
        "run_at": "document_start"
      }
    ]
}

What do I need to add to it to allow me to inject the code into the tab?

//UPDATE

To clarify, I have a context menu that when clicked opens a new tab and points it at the local file enter.html. the page just consists of an input box and a button. when clicked the button should send whats in the input box back to the background script using chrome.extension.sendMessage(). But it appears you can't inject a script from the extension into the page (which would allow it to communicate) nor can you directly via inline or seperate js file include anything within the chrome namespace in the enter.html code as this violates the default CSP, which if possible I would like to keep as-is.

I have tried editing the CSP slightly but without any effect. I added "content_security_policy": "script-src 'self' chrome-extension://adcfbbpepclgchodmdfbijpjhkgcamcg/; object-src 'self'" as well as adding the specific pages at the end.

I don't actually have any fully written pages as none of it works so I have no way to test what works in terms of message passing.

Upvotes: 1

Views: 790

Answers (2)

wezternator
wezternator

Reputation: 167

I solved this by using the addEventListener() to attach onto the buttons so as not to get in the way of the default CSP.

Upvotes: 1

Sudarshan
Sudarshan

Reputation: 18534

Problems in your code

  • You can not inject script to any of Extension Pages
  • chrome-extension://adcfbbpepclgchodmdfbijpjhkgcamcg/* is an invalid pattern, the docs are not updated on this.
  • Are you invoking chrome.extension.getBackgroundPage() from section which is relevant to chrome.* API, the CSP error is cause of this.

Suggestions

  • Why don't you add enter_content.js to list of scripts being used by page which is opened, instead of invalid injection.

Upvotes: 0

Related Questions