I'm trying to get the extension to listen for tab updates, take the URL, send that to the popup, then have the popup send the URL to my server. When the popup is open, everything works exactly as I expect it to. When I close the popup, however, the service worker stops listening for tab updates, so everything stops working. It seems like this would have been really easy to do with Manifest V2 with persistent backgrounds, but service workers don't seem to do that?
Here's the code:
background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if (changeInfo.url){
chrome.tabs.sendMessage({
msg: changeInfo.url
})
}
})
popup.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
console.log("From popup.js")
console.log(request.msg)
$.getJSON("https://api.ipify.org?format=json", function(data) {
const ip = (data.ip)
const sid = socket.id
socket.emit('new url', request.msg, ip, sid)
})
})
Again, this all works perfectly as long as the popup is open, but when the popup is closed, the background script stops listening and firing. Manifest.JSON includes 'tabs' in permissions, not sure if I maybe need something else.
--EDIT-- Showing some more code:
popup.js
var socket = io.connect('http://my_ip_address');
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
console.log("From popup.js")
console.log(request.msg)
$.getJSON("https://api.ipify.org?format=json", function(data) {
const ip = (data.ip)
const sid = socket.id
socket.emit('new url', request.msg, ip, sid)
})
})
background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if (changeInfo.url){
chrome.runtime.sendMessage({
msg: changeInfo.url
})
}
})
app.py
from flask import Flask, request, json, Response, render_template, session
from flask_cors import CORS
from flask_socketio import SocketIO, send
@socketio.on('new url')
def handle_new_url(url, ip, sid, methods=["GET"]):
print("attempting to print url")
Assuming that the fix is that I need to bypass popup.js and to instead have background.js speak directly to app.py, then the solution seems to be to just socket.emit from the background straight to the server. However, this doesn't work because background.js doesn't know what sockets are -- popup.js can use socketio because I have it imported in popup.html.
EDIT 2
new background.js:
var socketscript = document.createElement('script')
socketscript.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js')
document.head.appendChild(socketscript)
var socket = io.connect('my_ip_address');
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if (changeInfo.url){
socket.emit('new url', changeInfo.url, 1, 2)
}
})