I’m trying to write a chrome extension that plays video files by looking for certain attributes and syntaxes in the image filename associated with the video.
What I have so far:
Here’s what I have in manifest.json
{
"manifest_version": 3,
"name": "Image Context Video Player",
"version": "1.0",
"description": "Plays a video when right-clicking relevant images.",
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"permissions": [
"contextMenus",
"activeTab",
"scripting",
"webNavigation",
"storage"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"all_frames": true
}
]
}
Here’s background.cs:
chrome.runtime.onInstalled.addListener(async () => {
console.log("Extension installed");
// Read the base URL, attribute, and separator from text files
const baseUrlResponse = await fetch(chrome.runtime.getURL('base-url.txt'));
const baseUrl = await baseUrlResponse.text();
const attributeResponse = await fetch(chrome.runtime.getURL('attribute.txt'));
const attribute = await attributeResponse.text();
const separatorResponse = await fetch(chrome.runtime.getURL('separator.txt'));
const separator = await separatorResponse.text();
// Store them in local storage
chrome.storage.local.set({
video_base_url: baseUrl.trim(),
attribute: attribute.trim(),
separator: separator.trim()
}, () => {
console.log("Base URL, attribute, and separator stored.");
console.log("Base URL:", baseUrl.trim());
console.log("Attribute:", attribute.trim());
console.log("Separator:", separator.trim());
});
chrome.contextMenus.create({
id: "playVideo",
title: "Play Video",
contexts: ["image"],
visible: false // Start with the menu hidden
});
console.log("Context menu created");
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'updateContextMenu') {
console.log("Updating context menu visibility:", message.isRelevant);
chrome.contextMenus.update("playVideo", {
visible: message.isRelevant
});
}
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "playVideo") {
console.log("Context menu item clicked");
chrome.storage.local.get('videoUrl', function(data) {
const videoUrl = data.videoUrl;
console.log("Playing video from URL:", videoUrl);
chrome.tabs.sendMessage(tab.id, {
action: 'playVideoOverlay',
videoUrl: videoUrl
});
});
}
});
chrome.webNavigation.onCompleted.addListener(function(details) {
console.log("Injecting content script into tab:", details.tabId);
chrome.scripting.executeScript({
target: {tabId: details.tabId, allFrames: true},
files: ['content.js']
});
}, {url: [{urlMatches: '<all_urls>'}]});
And here is content.js:
document.addEventListener('contextmenu', function (event) {
const element = event.target;
console.log("Context menu opened on element:", element);
if (element.tagName === 'IMG') {
window.rightClickedImgElement = element;
let isRelevant = false;
let videoUrl = "";
const imgSrc = element.getAttribute("src");
// Retrieve the attribute and separator from storage
chrome.storage.local.get(['video_base_url', 'attribute', 'separator'], function(data) {
const baseUrl = data.video_base_url;
const attribute = data.attribute;
const separator = data.separator;
let currentElement = element;
let attrib = null;
// Traverse up the DOM to find the first element with the attribute
while (currentElement) {
if (currentElement.hasAttribute(attribute)) {
attrib = currentElement.getAttribute(attribute);
break;
}
currentElement = currentElement.parentElement;
}
if (attrib && attrib.toLowerCase().endsWith(".mp4")) {
isRelevant = true;
// Extract the folder name from the image src path
const url = new URL(imgSrc);
const pathParts = url.pathname.split('/');
const folderName = pathParts.slice(0, -1).join('/'); // The folder name
// Determine the base filename for the video file
let videoFileName;
if (pathParts[pathParts.length - 1].toLowerCase().includes(separator.toLowerCase())) {
const baseFileName = pathParts[pathParts.length - 1].split(separator)[0];
videoFileName = baseFileName + attrib.substring(attrib.lastIndexOf('.'));
} else {
videoFileName = attrib;
}
// Construct the full video URL
videoUrl = `${baseUrl}${folderName}/${videoFileName}`;
console.log("Image relevance:", isRelevant);
console.log("Video URL:", videoUrl);
chrome.runtime.sendMessage({
action: 'updateContextMenu',
isRelevant: isRelevant
});
if (isRelevant) {
chrome.storage.local.set({ videoUrl: videoUrl });
}
} else {
chrome.runtime.sendMessage({
action: 'updateContextMenu',
isRelevant: false
});
}
});
} else {
window.rightClickedImgElement = null;
chrome.runtime.sendMessage({
action: 'updateContextMenu',
isRelevant: false
});
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'playVideoOverlay') {
const videoUrl = message.videoUrl;
console.log("Playing video from URL:", videoUrl);
playVideoOverlay(videoUrl);
}
});
function playVideoOverlay(videoUrl) {
if (!videoUrl) {
console.log("No video URL provided, exiting");
return;
}
console.log("Creating video overlay");
const overlay = document.createElement("div");
overlay.style.position = "fixed";
overlay.style.top = 0;
overlay.style.left = 0;
overlay.style.width = "100%";
overlay.style.height = "100%";
overlay.style.backgroundColor = "rgba(0, 0, 0, 0.8)";
overlay.style.display = "flex";
overlay.style.alignItems = "center";
overlay.style.justifyContent = "center";
overlay.style.zIndex = 10000;
const video = document.createElement("video");
video.src = videoUrl;
video.controls = true;
video.autoplay = true;
video.style.maxWidth = "90%";
video.style.maxHeight = "90%";
overlay.appendChild(video);
document.body.appendChild(overlay);
const removeOverlay = () => {
console.log("Removing video overlay");
overlay.remove();
video.pause();
};
overlay.addEventListener("click", removeOverlay);
video.addEventListener("ended", removeOverlay);
}
I’m definitely doing something wrong because I’m getting the exception “Extension context invalidated” whenever I right click on an img tag, I haven’t even gotten to the point of verifying that the content script works correctly when used on img tag that have the expected attribute in is hierarchy (speaking of which, nothing I try to log is showingg up the devtools log console…. I only appear to be able to specify logs coming from background.cs, none from content.cs. At least that’s all that’s ever showing in the service worker window for the extension I don’t think I’m injecting content.js correctly either because it’s not even showing the message “Injecting content script…” that is suppose to inject content.js into every frame.
EDIT: Per a suggestion below, the error message is not showing up, and most of the extension appears to be working correctly now. The fix was to shut down chrome and restart it.
When I right click on an image that I do see the log message indicating that that this code is getting called in background.js:
console.log("Updating context menu visibility:", message.isRelevant);
chrome.contextMenus.update("playVideo", {
visible: message.isRelevant
});
However, I don’t see any log messages from the content.js script so I cannot identify what I am still doing wrong, because my menu option isn’t showing up even when I right click on images where message.isRelevant
is true.
3