Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

can you write a chrome extension that complies with chromes content security policy. if…

  1. User

    can you write a chrome extension that complies with chromes content security policy. if the user is on a youtube video page and there is the letters SV and a youtube link right after it in the excerpt of the video description it should launch, when the main icon is clicked, into a full black screen with two videos one on top of the other, the video urls are the one on the youtube page and the one after the letters SV. escape key should close it and recommended videos that are in the videos that are clicked on should open where the video they were in was and not a new tab.

  2. Assistant

    Creating a Chrome extension with the functionality you described involves several steps, including interacting with YouTube's DOM, handling user interactions, and dynamically injecting video players. Below is a simplified version of such an extension. Please note that depending on YouTube's frequent updates to their site structure, additional adjustments might be necessary to ensure compatibility.

    Overview

    1. Manifest File (manifest.json)

      • Defines the extension's permissions, background scripts, and content scripts.
    2. Content Script (content.js)

      • Scans the YouTube video description for the pattern "SV" followed by a YouTube link.
      • Stores the secondary video URL for later use.
    3. Popup HTML (popup.html) and JavaScript (popup.js)

      • Handles the main icon click.
      • Injects a full-screen overlay with two embedded videos.
      • Handles the Escape key to close the overlay.
      • Ensures that recommended videos open in the same tab.
    4. CSS (styles.css)

      • Styles the full-screen overlay and video containers.

    1. manifest.json

    {
      "manifest_version": 3,
      "name": "YouTube SV Video Launcher",
      "version": "1.0",
      "description": "Launches two YouTube videos from description when activated.",
      "permissions": ["activeTab", "scripting"],
      "action": {
        "default_popup": "popup.html",
        "default_icon": {
          "16": "icons/icon16.png",
          "48": "icons/icon48.png",
          "128": "icons/icon128.png"
        }
      },
      "content_scripts": [
        {
          "matches": ["https://www.youtube.com/watch*"],
          "js": ["content.js"]
        }
      ],
      "icons": {
        "16": "icons/icon16.png",
        "48": "icons/icon48.png",
        "128": "icons/icon128.png"
      }
    }
    

    Notes:

    • Ensure you have icon files in the specified directory.
    • scripting permission is required for injecting scripts.

    2. content.js

    // content.js
    
    let svVideoUrl = null;
    
    // Function to extract SV video URL
    function extractSVVideoUrl() {
      const description = document.querySelector('#description') || document.querySelector('#meta #description');
      if (description) {
        const text = description.innerText;
        const svIndex = text.indexOf('SV');
        if (svIndex !== -1) {
          const afterSV = text.substring(svIndex + 2).trim();
          const urlMatch = afterSV.match(/https?:\/\/www\.youtube\.com\/watch\?v=[\w-]{11}/);
          if (urlMatch) {
            svVideoUrl = urlMatch[0];
            // Store in page's dataset for access by popup
            document.body.dataset.svVideoUrl = svVideoUrl;
          }
        }
      }
    }
    
    // Run extraction on page load
    extractSVVideoUrl();
    

    Notes:

    • This script searches for "SV" in the video description and extracts the subsequent YouTube link.
    • It stores the extracted URL in the page's dataset for access by the popup.

    3. popup.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>YouTube SV Video Launcher</title>
      <link rel="stylesheet" href="styles.css">
    </head>
    <body>
      <button id="launchButton">Launch Videos</button>
    
      <script src="popup.js"></script>
    </body>
    </html>
    

    4. popup.js

    // popup.js
    
    document.getElementById('launchButton').addEventListener('click', async () => {
      // Query the active tab
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
      // Execute a script to get the SV video URL from the page's dataset
      chrome.scripting.executeScript(
        {
          target: { tabId: tab.id },
          function: () => document.body.dataset.svVideoUrl,
        },
        (results) => {
          const svVideoUrl = results[0].result;
          if (svVideoUrl) {
            chrome.scripting.executeScript(
              {
                target: { tabId: tab.id },
                func: launchVideos,
                args: [tab.url, svVideoUrl],
              }
            );
          } else {
            alert('SV video URL not found in description.');
          }
        }
      );
    });
    
    // Function to inject the overlay with videos
    function launchVideos(mainVideoUrl, svVideoUrl) {
      // Prevent multiple overlays
      if (document.getElementById('sv-overlay')) return;
    
      // Create overlay
      const overlay = document.createElement('div');
      overlay.id = 'sv-overlay';
    
      // Create container
      const container = document.createElement('div');
      container.id = 'sv-container';
    
      // Create video iframes
      const mainIframe = document.createElement('iframe');
      mainIframe.src = `https://www.youtube.com/embed/${getYouTubeID(mainVideoUrl)}?autoplay=1`;
      mainIframe.allow = "autoplay; encrypted-media";
      mainIframe.allowFullscreen = true;
    
      const svIframe = document.createElement('iframe');
      svIframe.src = `https://www.youtube.com/embed/${getYouTubeID(svVideoUrl)}?autoplay=1`;
      svIframe.allow = "autoplay; encrypted-media";
      svIframe.allowFullscreen = true;
    
      // Append iframes to container
      container.appendChild(mainIframe);
      container.appendChild(svIframe);
    
      // Append container to overlay
      overlay.appendChild(container);
      document.body.appendChild(overlay);
    
      // Add keydown listener to close on Escape
      function escListener(e) {
        if (e.key === 'Escape') {
          closeOverlay();
        }
      }
    
      document.addEventListener('keydown', escListener);
    
      // Function to close overlay
      function closeOverlay() {
        document.body.removeChild(overlay);
        document.removeEventListener('keydown', escListener);
      }
    
      // Ensure recommended videos open in the same tab
      overrideLinks();
    
      function overrideLinks() {
        const links = document.querySelectorAll('a');
        links.forEach(link => {
          link.addEventListener('click', (e) => {
            e.preventDefault();
            const url = link.href;
            if (url.startsWith('https://www.youtube.com/watch')) {
              window.location.href = url;
            }
          });
        });
      }
    
      // Utility to extract YouTube video ID
      function getYouTubeID(url) {
        const regex = /v=([a-zA-Z0-9_-]{11})/;
        const match = url.match(regex);
        return match ? match[1] : null;
      }
    }
    

    Notes:

    • The popup script retrieves the current tab's URL and the SV video URL from the content script.
    • It then injects an overlay with two embedded YouTube players.
    • The Escape key listener allows users to close the overlay.
    • Recommended videos within the overlay are overridden to open in the same tab.

    5. styles.css

    /* styles.css */
    
    #sv-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: black;
      z-index: 9999;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    }
    
    #sv-container {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
    
    #sv-container iframe {
      width: 80%;
      height: 45vh;
    }
    

    Notes:

    • Styles the overlay to cover the entire screen with a black background.
    • Two videos are stacked vertically with some spacing.

    Additional Considerations

    1. Content Security Policy (CSP):

      • Manifest V3 enforces stricter CSP. Inline scripts and certain eval-like functions are disallowed.
      • All JavaScript should be in separate .js files.
      • Ensure that any resources loaded comply with YouTube's embedding policies.
    2. YouTube Embedding Restrictions:

      • Some videos might have embedding disabled.
      • Ensure that both videos allow embedding to avoid playback issues.
    3. Dynamic Content Loading:

      • YouTube dynamically loads content; ensure that the content script runs after the necessary elements are available or use mutation observers as needed.
    4. Error Handling:

      • Add more robust error handling for cases where URLs aren't found or embedding fails.
    5. Permissions:

      • The activeTab and scripting permissions are essential for injecting scripts and modifying the current page.
    6. Icon Files:

      • Ensure that you have appropriate icon files (icon16.png, icon48.png, icon128.png) in an icons directory.

    Testing the Extension

    1. Prepare the Files:

      • Create a directory for your extension.
      • Add the manifest.json, content.js, popup.html, popup.js, styles.css, and icon files to this directory.
    2. Load the Extension:

      • Open Chrome and navigate to chrome://extensions/.
      • Enable "Developer mode" using the toggle in the top right corner.
      • Click "Load unpacked" and select your extension's directory.
    3. Use the Extension:

      • Navigate to a YouTube video page.
      • Ensure the video description contains "SV" followed by a valid YouTube link.
      • Click the extension icon and then the "Launch Videos" button in the popup.
      • A full-screen overlay with two videos should appear.
      • Press Escape to close the overlay.

    Disclaimer

    This extension is a basic implementation and may require enhancements for production use. Be mindful of YouTube's Terms of Service and ensure that your extension complies with all relevant guidelines and policies.