OrangeBike
OrangeBike

Reputation: 145

execute javascript in a new tab using chrome extension

so what I am trying to do is that on one tab I want to press a button on my Chrome extension which will open a new tab and I want some script to be executed in that new tab. BUT ONLY WHEN I PRESS THE BUTTON ON THE EXTENSION.

here is my manifest.json

{
    "manifest_version": 2,
    "name": "extension",  
    "description": "extension",  
    "version": "1.0",    
    "browser_action": { 
        "default_popup": "popup.html"  
    },
    "background": {
        "service_worker": "background.js"
      },
    "content_scripts": [
        {
          "matches": ["https://*.somewebsite.com/*"],
          "js": ["myScript.js"]
        }
      ],
    "permissions": ["tabs", "<all_urls>", "http://*/",
        "https://*/"]
}

popup.html

<!doctype html>  
<html>  
    <head><title>Extension</title></head>  
    <body>
        <h2>My Extension</h2>
        <button id="myButton">Press Me!</button> 
        <script src="popup.js"></script> 
    </body>
</html>

popup.js (this opens a new tab from the current tab by executing "openTab.js")

function injectTheScript() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.executeScript(tabs[0].id, {file: "openTab.js"});
    });
}

document.getElementById('myButton').addEventListener('click', injectTheScript)

background.js

chrome.runtime.onInstalled.addListener(() => {
  console.log('extension is on!');
});

Now this all works but the thing is the myScript.js is executed all the time on all new tabs because of being declared in manifest.json. However, I want it to be executed on new tabs ONLY when I press the "Press Me!" button.

Upvotes: 1

Views: 2497

Answers (2)

Phạm Huy Ph&#225;t
Phạm Huy Ph&#225;t

Reputation: 1116

To run a script in the tab's runtime environment, add world: 'MAIN' to config of chrome.scripting.executeScript. for example

chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ['myScript.js'],
    world: 'MAIN'
});

reference: https://developer.chrome.com/docs/extensions/reference/scripting/#type-ExecutionWorld

Upvotes: 0

Jaco
Jaco

Reputation: 36

I have only tried this with the manivest v3 so not sure if it will work with v2.

When you execute this inside your background.js, it will load your content script on the current tab when it is executed. Put it inside of an event handler to only execute when needed.

chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ['myScript.js']
});

And then remove this from you manifest.json

"content_scripts": [
    {
      "matches": ["https://*.somewebsite.com/*"],
      "js": ["myScript.js"]
    }
  ],

And add:

"permissions": [
    "activeTab"
]

https://developer.chrome.com/docs/extensions/mv3/content_scripts/#programmatic

Upvotes: 2

Related Questions