0

I am trying to create a Chrome extension where I can see if a youtube url is no longer active by seeing if the Video unavailable text is on the screen. I am trying to have this automated so I don't have to do this manually. These are my scripts.

I am first testing with just trying to change the page background color, in the end I'm going to be doing query selectors on the page but I can't seem to figure out how to get access to the page dom once the tab is fully opened. I give it a 60 second wait time to ensure the active tab is open because my internet is a bit slow.

I have been trying to figure this out for past 3-4 hours looking at several overflow questions as well as github repos to try and figure out how I can do this. I need to be able to do it from the popup window and communicate to the active tab because otherwise I don't think this can be automated since the extension popup on the browser corner would close once tab is opened/closed from what I have tested.

I also have jquery in the project folder, get the jquery.min.js and it should be good.

Manifest.json

{
    "name": "Youtube Chrome Extension",
    "version": "0.0.0.1",
    "content_security_policy": {
        "extension_pages": "script-src 'self'; object-src 'self'"
    },
    "description": "Youtube Chrome Extension",
    "action": {
        "default_popup": "Main.html"
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "css": ["CSS/style.css"],
            "match_origin_as_fallback": true
        }
    ],
    "host_permissions": ["<all_urls>"],
    "permissions":[
        "activeTab",
        "scripting",
        "contextMenus", 
        "tabs",
        "webNavigation",
        "webRequest"
    ],
    "manifest_version": 3,
    "icons": {
        "16": "Youtube.png",
        "48": "Youtube.png",
        "128": "Youtube.png"
    }
}

Automation.html

<html>
<head>
    <script type="text/javascript" src="CDN/jquery.min.js"></script>
    <script type="text/javascript" src="JS/main2.js"></script>
    <script type="text/javascript" src="JS/message.js"></script>
    <br />
    <div id="player"></div>
<div id="InfoHere" style="height:300px;overflow-y: scroll">
    <span style="font-size:20px">Time: <span id="TimerText"></span></span>
</div>
  <div id="SongURL" style="font-size:30px"></div>
    <button id="StartAutomation" style="height:100px;width:200px;font-size:20px;"> Start</button>
    <button id="create" style="height:100px;width:200px;font-size:20px;"> Save file</button>

</head>

Main.html

<html>
<head>
    <script type="text/javascript" src="CDN/jquery.min.js"></script>
    <script type="text/javascript" src="JS/main.js"></script>
    <button id="AutomationMenu" style="height:100px;width:200px;font-size:20px;">
       Open automation window
    </button>
</head>

pageScript.js

// Include guard: only execute once
if (!injected) {
  injected = true;
  init();
}

function init() {
  // Get ready to receive a command
  chrome.runtime.onMessage.addListener(function (
    message,
    sender,
    sendResponse
  ) {
    if (message.action == "colorBackground") {
      console.log(request);
      console.log(sender);
      console.log(sendResponse);
      var emptyState = document.getElementsByClassName(
        "promo-title style-scope ytd-background-promo-renderer"
      );
      console.log(emptyState);
      document.body.style.backgroundColor = message.color;
    }
  });
}

main2.js

document.addEventListener("DOMContentLoaded", () => {
  $("#StartAutomation").click(function () {
    var songURLs = ["OXBxUDJtibw"];
    for (var x = 0; x < 1; x += 1) {
      chrome.tabs.create(
        { url: `https://www.youtube.com/watch?v=${songURLs[x]}` },
        getPageData
      );
    }
  });
  $("#create").click(function () {
    var textToWrite = document.getElementById("textbox").value;
    var textFileAsBlob = new Blob([textToWrite], { type: "text/plain" });
    var fileNameToSaveAs = "Test.txt";
    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null) {
      downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    } else {
      downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
      downloadLink.onclick = destroyClickedElement;
      downloadLink.style.display = "none";
      $("#InfoHere").appendChild(downloadLink);
    }
    downloadLink.click();
  });
});
var myTab;
var timer = 60;
var intervalId;
const timerText = function () {
  timer = timer - 1;
  $("#TimerText").text(timer.toString());
  if (timer < 0) {
    clearInterval(intervalId);
  }
};

function getPageData() {
  $("#TimerText").text("60");
  intervalId = setInterval(timerText, 1000);
  setTimeout(function () {
    chrome.tabs.query(
      {
        currentWindow: true,
        active: true,
      },
      function (tabs) {
        chrome.scripting.executeScript(
          { target: { tabId: tabs[0].id }, files: ["JS/pageScripts.js"] },
          function () {
            chrome.tabs.sendMessage(tabs[0].id, {
              action: "backgroundColor",
              color: "green",
            });
          }
        );
      }
    );
  }, 60000);
}

main.js

document.addEventListener("DOMContentLoaded", () => {
  var StartAutomation = document.getElementById("AutomationMenu");
  StartAutomation.addEventListener("click", (e) => {
    chrome.windows.create({
      height: 1000,
      width: 800,
      url: chrome.runtime.getURL("../Automation.html"),
      type: "popup",
    });
  });
});

My js files are in a folder called JS and for youtube.png I just used a simple youtube logo from google images for that.

If there is anything else that is needed, please let me know. Also, please show solution as well as explaining it. I'd love to see solution because explanation without a solution is very hard for me to understand because I am still fairly new to chrome extension development. Thanks!!

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • if dropping a project zip on media file sharing is easier for people to help out, let me know thanks! – NoNameAccount Jun 19 '22 at 05:33
  • Since the popup closes when a tab is opened you need to move the controlling logic from the popup into the background script. The popup's click handler will send a message to the background script, which will handle the rest. – wOxxOm Jun 19 '22 at 05:36
  • I had a background script earlier when I was testing this and then I didn't see a need for it because I am opening/creating a new tab. Will a background script be able to send a response back of the new tab being created once it is fully loaded? I am unsure how to do that, can you provide code example if you can? I'd appreciate it, thanks! (I need to be able to see if a specific class is rendered on the new tab page loaded) – NoNameAccount Jun 19 '22 at 05:40
  • the popup is on new window popup in case people are confused. not a popup like in the corner on the extension click – NoNameAccount Jun 19 '22 at 05:42
  • See [messaging](https://developer.chrome.com/extensions/messaging) for some examples. When a new tab is opened, the `action` popup is closed and that's the end of it. If you want to display the result you can open a new window using chrome.windows.create or add an element to the page and [style it as a popup manually](https://stackoverflow.com/a/25100953). – wOxxOm Jun 19 '22 at 05:49
  • thanks, I'll take a look at that tomorrow and test them out, appreciate it! – NoNameAccount Jun 19 '22 at 05:51

0 Answers0