According to chrome extension documentation,

Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).

Read: http://developer.chrome.com/extensions/contentSecurityPolicy.html#JSExecution

Use in popup.js as

document.addEventListener('DOMContentLoaded', function () {
      document.querySelector('button').addEventListener('click', main);      
});
function main() {
    var source = document.getElementById('source').value;
    document.getElementById("result").innerHTML = source;
}
Answer from Tamil Selvan C on Stack Overflow
๐ŸŒ
Chrome Web Store
chromewebstore.google.com โ€บ detail โ€บ run-javascript โ€บ lmilalhkkdhfieeienjbiicclobibjao
Run Javascript - Chrome Web Store
| Feature | This Extension | Others ... execution prevention | โŒ Script conflicts | ## โšก Get Started in 60 Seconds: 1. Install the extension 2. Visit any website you want to customize 3. Click the extension icon in your toolbar ...
๐ŸŒ
Krasimirtsonev
krasimirtsonev.com โ€บ blog โ€บ article โ€บ Chrome-Extension-run-JavaScript-in-the-context-of-the-current-page
Chrome Extension: run JavaScript in the context of the current page
That's because Content Security Policy. In my case this happens when I'm operating with https sites. So, it looks like this tricky solution, the one with injecting script tag, doesn't work. Luckily Chrome offers another solution - chrome.tabs.executeScript method.
๐ŸŒ
GitHub
gist.github.com โ€บ danharper โ€บ 8364399
Bare minimum Chrome extension to inject a JS file into the given page when you click on the browser action icon. The script then inserts a new div into the DOM. ยท GitHub
Bare minimum Chrome extension to inject a JS file into the given page when you click on the browser action icon. The script then inserts a new div into the DOM. - background.js
๐ŸŒ
Google Support
support.google.com โ€บ adsense โ€บ answer โ€บ 12654
Allow JavaScript in your browser - Google AdSense Help
This article describes how to allow JavaScript in Google Chrome, which is required to display some media, including some Google ads. It also provides links to the documentation to turn on, activate, o
๐ŸŒ
GitHub
github.com โ€บ ao โ€บ RunJavascript_ChromeExtension
GitHub - ao/RunJavascript_ChromeExtension: A simple Chrome Extension that allows you to run some Javascript each time you are on that domain.
# Clone and set up in under 2 minutes git clone [repository-url] cd RunJavascript_ChromeExtension bun install # Lightning-fast dependency installation bun test # Comprehensive test suite # Load in Chrome developer mode and you're ready! This project uses Bun - the fastest JavaScript runtime for blazing-fast development.
Starred by 17 users
Forked by 8 users
Languages ย  JavaScript 85.5% | CSS 6.7% | Shell 4.3% | HTML 3.5%
Find elsewhere
๐ŸŒ
Engabao
engabao.com โ€บ single-press-chrome-extension-to-run-js-on-a-website-manifest-version-3
Single click chrome extension to run JS on a website (manifest version 3) | Engabao.com
It is easier than you think, just follow this tutorial for creating an extension that uses manifest version 3. In this example we will use javascript to attach some CSS to a website in one click. 1. Add a new folder on your machine and create these 3 files inside it: manifest.json โ€“ Will contain the info that tells Chrome how to handle your extension backgroud.js โ€“ Will inject your script into the website loaded in current chrome tab injectedscript.js โ€“ Will contain the script to inject
๐ŸŒ
Chrome Developers
developer.chrome.com โ€บ docs โ€บ chrome extensions โ€บ get started โ€บ run scripts on every page
Run scripts on every page | Get started | Chrome for Developers
October 4, 2022 - Extensions can run scripts that read and modify the content of a page. These are called content scripts. They live in an isolated world, meaning they can make changes to their JavaScript environment without conflicting with their host page or other extensions' content scripts.
Top answer
1 of 2
13

So I think that the simple solution is just to create a content script and there to wait until the page is load :

manifest.json

{
    "manifest_version": 2,
    "name": "Getting started example",
    "description": "This extension shows a Google Image search result for the   current page",
    "version": "1.0",
    "content_scripts": [
        {
            //Set your address you want the extension will work in mataches!!!
            "matches": ["http://mail.google.com/*", "https://mail.google.com/*"],
            "js": ["content.js"],
            "run_at": "document_end"
        }
    ],
    "permissions": ["activeTab", "https://ajax.googleapis.com/"],
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    }
}

content.js

window.onload=function(){
     console.log("page load!");
}

You could also use with message passing between background.js and your content page and to check that tab is loaded but for your case I think it's enough.

2 of 2
1

This is how I do:

manifest.json

...
"background": {
    "scripts": [
        "assets/js/background.js"
    ],
    "persistent": false
},
....

background.js

function openOrFocusOptionsPage() {
    var optionsUrl = chrome.extension.getURL('popup.html'); 
    chrome.tabs.query({}, function(extensionTabs) {
        var found = false;
        for(var i=0; i < extensionTabs.length; i++) {
            if(optionsUrl == extensionTabs[i].url) {
                found = true;
                chrome.tabs.update(extensionTabs[i].id, {"selected": true});
            }
        }
        if(found == false) {
            chrome.tabs.create({url: "popup.html"});
        }
    });
}

chrome.extension.onConnect.addListener(function(port) {
    var tab = port.sender.tab;


    port.onMessage.addListener(function(info) {
        var max_length = 1024;
        if(info.selection.length > max_length)
            info.selection = info.selection.substring(0, max_length);
        openOrFocusOptionsPage();
    });
});


chrome.browserAction.onClicked.addListener(function(tab) {
    openOrFocusOptionsPage();
});
๐ŸŒ
Chrome Developers
developer.chrome.com โ€บ docs โ€บ chrome extensions โ€บ reference โ€บ api โ€บ chrome.scripting
chrome.scripting | API | Chrome for Developers
A JavaScript function to inject. This function will be serialized, and then deserialized for injection. This means that any bound parameters and execution context will be lost. Exactly one of files or func must be specified. ... The origin for a style change. See style origins for more info. ... Injects a script into a target context. By default, the script will be run at document_idle, or immediately if the page has already loaded.
๐ŸŒ
Stack Exchange
softwarerecs.stackexchange.com โ€บ questions โ€บ 54629 โ€บ chrome-extension-which-allows-custom-javascript-code-to-run-after-page-load
Chrome extension which allows custom javascript code to run after page load - Software Recommendations Stack Exchange
So it would be the equivalent to opening up and running some code in the Developer Tools console after the page loads. I'd like something which would automate this process. ... Try Tampermonkey. By default it cannot access filesystem resources, though. Enable it inside the config panel. You still would have to convert your snippets / JS ifles into a specific userscripts format (.user.js), stored "inside Tampermonkey".
Top answer
1 of 2
7

You cannot invoke any methods of an extension from within a web page. However, it's possible to inject a content script into the web page, and use sendMessage and onMessage, or onConnect and connect.

To edit an extension: Visit chrome://extensions page, and enable the Developer mode. Unpack an extension and/or visit the extension's directory. Edit the manifest.json file, and add the necessary lines (see here).

Add an event event listener at the background page. Add a poller in the content script, eg:

// Content script
var poller = window.setInterval(function() {
   if (document.documentElement.getAttribute('extensionCalled')) {
       chrome.extension.sendMessage({"anyname": "anything"}, function() {
           /*optional callback function.*/alert("Something happened")
       });
       clearInterval(poller);
   }
}, 200);

// Background
chrome.extension.onMessage.addListener(function(request, sender, callback) {
    if (request.anyname == "anything") {
        function_logic_here();
        //Optionally, callback:
        callback();
    }
});

See also

  • Chrome extension - retrieving Gmail's original message - Using DOM events to communicate between a page and extension (recommended)
  • MDN: postMessage - It can be used to communicate between a page and extension (this method may cause conflicts when the page itself is also using the message events).

References:

  • Extension messaging
  • Content scripts
  • Content scripts in extensions
2 of 2
6

It would only be possible if the extension provides an interface to do it. Extensions run in an isolated environment, so you don't have direct access to any of their functions.

The closest they get is content scripts, which have access to the DOM. Because of that, you can communicate using events, but obviously the extension would need to set up event handlers for them, so it completely depends on the extension.

๐ŸŒ
Chrome for Developers
developer.chrome.com โ€บ docs โ€บ chrome devtools โ€บ run snippets of javascript
Run snippets of JavaScript | Chrome DevTools | Chrome for Developers
October 12, 2015 - Focus your cursor anywhere inside of DevTools. Press Control+Shift+P (Windows/Linux) or Command+Shift+P (Mac) to open the Command Menu. Start typing Snippet, select Create new snippet, then press Enter to run the command.