Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension as static server

I would like to make a chrome extension that simply serve static content from a defined directory. As usual the static directory will be in the extension repository.

I would like the extension to open in a complete tab. For example, my grease-monkey extension opena a tab with a url that starts with chrome-extension://. The tab is this requirement that blocks me.

Someone know an example of such a plugin? A hello world in a new tab extension would fit my needs.

like image 618
user983716 Avatar asked Feb 11 '23 00:02

user983716


1 Answers

Extension page inside a tab

This is pretty easy to achieve: all you have to do is to create a basic extension with a folder containing the page.html and the relative JavaScript and CSS files; then you can use the chrome.tabsAPI to create a new tab and display the page.html inside it.

Implementation

Following these steps, you'll be able to open a new tab containing a page hosted in your extension folder, which will have an URL like chrome-extension://<id>/page/page.html:

  1. Create an extension and the relative files for the manifest, background and the page you want to display. The extension's directory should then look like this:

    <root/>:
      - background.js
      - manifest.json
      - <page/>:
          - page.html
          - page.js
          - page.css
    
  2. Create a simple manifest.json file declaring the background page:

    {
        "manifest_version": 2,
        "name": "Some test",
        "version": "0",
    
        "background": {
            "scripts": ["/background.js"] 
        }
    } 
    
  3. Create the background.js script, where you will create the tab:

    chrome.tabs.create({url: "/page/page.html"});
    
  4. Create the page.html file, which is just a regular html page:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Test</title>
            <link rel="stylesheet" type="text/css" href="page.css"/>
        </head>
        <body>
            <script src="page.js"></script>
        </body>
    </html>
    
  5. Create the page.js script, which will run inside your page.html, and where you can do whatever you want:

    var h = document.createElement('h1');
    
    h.textContent = 'Hello World!';
    document.body.appendChild(h);
    

Result

The result of the above will be something like this:

result

like image 80
Marco Bonelli Avatar answered Feb 13 '23 15:02

Marco Bonelli