Making a Chrome Extension

I have a little personal project that is basically a web app to save and share links. Not very original, but its been fun to work on and explore some ideas. I decided I wanted to write a chrome extensions so I could quickly add a new link.

I started with ChatGPT:

How can I make a chrome extension to save the current URL?

I got back a full implementation which was actually pretty nice along with instructions on how to install it etc. Here’s interesting part:

document.getElementById('saveUrl').addEventListener('click', function() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var currentTab = tabs[0];
    console.log(currentTab.url); // Do something with the URL, like saving it to local storage or sending it to a server
  });
});

Seems cool except that No matter what I do I never see the console.log output, or I don’t know where to look for it. I tried asking GPT for advice and it gave me some things to try but none of them worked. Reading google’s docs I realized that the extension that GPT made for me was a V2 version

"manifest_version": 2,

and there is now V3 so I figured I would look for other example code and use V3 just to be up to date.

This also didn’t make things work, but I decided to just swap out the console.log for alert and now I was at least getting some output.

I spent a fair amount of time thinking about what sort of API I needed for the extension to be able to talk to my App. How would I handle auth etc? Do I want to build a form into the extension UX to all the user to add additional metadata etc. If I would have started coding right away I would have probably gone down this path. Instead I took a break to think about it some more.

Eventually I realized I don’t need to do any of that. I just need the app to open up a new tab on the page in my app which adds a new url with the url pre-populated. The app already knows how to deal with login/redirect etc, I can add whatever I want on the page so I don’t have to deal with any of those problems.

So I just need this little boilerplate:

async function getCurrentTab() {
  let queryOptions = { active: true, lastFocusedWindow: true };
  let [tab] = await chrome.tabs.query(queryOptions);
  return tab;
}

And then we just construct the new tab use based using the ADD_PAGE_URL + an encoded url param.

async function openTabForAdd() {
    var currentTab = await getCurrentTab();
    let encoded = encodeURIComponent(currentTab.url)
    let redirect = ADD_PAGE_URL+ '?url=${encoded}`
    chrome.tabs.create({ url:redirect});
}

On the backend the Django server looks for the url param and pre-populates a form. The extension is super simple and I can control the UX from the Django/htmx world instead of also having to invest in doing something complicated in the extension.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *