Search code examples
javascripturlgoogle-chrome-extension

Chrome Extension: How to convert a local HTML file into a URL to display?


I am currently developing a chrome extension, and am attempting to make one of my local HTML files into a URL so I can open it from my content script. One solution I found was to use:

chrome.tabs.create({url: chrome.extension.getURL('notes.html')});

This did not work though. Some people have reported that content scripts may not work with all of the chrome extension API. I need this function to work from my content script though, to make sure it will fire when I need it to. I also found:

var urlChanged = window.url.createObjectURL("notes.html");
window.open(urlChanged);

This did not work either. I ended with trying:

var urlChanged = chrome.runtime.getURL("notes.html");
window.open(urlChanged);

A new tab opens, but I only get a blank HTML page. I was wondering if anyone can give me some insight as to why none of these methods may be working?

tl;dr My content script does not want to open and display a local HTML file I made. I used multiple methods to try and open it, but the file does not want to open from the content script. The HTML file is in the same extension folder as the content script and manifest.json. Any help with this would be appreciated!


Solution

    • To open your extension's page via window.open() in a content script you'll have to expose it using web_accessible_resources in manifest.json. It'll make your extension detectable from web though.

      "web_accessible_resources": [
        "notes.html"
      ]
      

    • A better solution is to send a message from the content script to the background script, which can use chrome.tabs API to open your extension page.

      It's a better solution because window.open from a web page tab may be blocked by the anti-popup policy. And also because you don't expose your extension's pages to the web.

      manifest.json should declare the background script:

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

      content script simply sends a message:

      chrome.runtime.sendMessage({action: 'openNotes'});
      

      background.js does the work:

      chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
        switch (msg.action) {
          case 'openNotes':
            chrome.tabs.create({
              url: '/notes.html',
              active: true,
              index: sender.tab.index + 1,
              openerTabId: sender.tab.id,
            });
            return;
        }
      });