Skip to content

Instantly share code, notes, and snippets.

@bitlather
Last active November 21, 2019 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitlather/08febadcd09cc5a0431b37783b1e0a09 to your computer and use it in GitHub Desktop.
Save bitlather/08febadcd09cc5a0431b37783b1e0a09 to your computer and use it in GitHub Desktop.
function copyToClipboard(str) {
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
str = $("h1.title").textContent
+ "\n" + window.location.href
+ "\n" + "Description:"
+ "\n" + $("yt-formatted-string.content").textContent.split("\n»")[0]
copyToClipboard(str);
@bitlather
Copy link
Author

bitlather commented Nov 21, 2019

Creating Chrome Extension

From https://developer.chrome.com/extensions/getstarted

manifest.json

{
  "name": "Youtube Copy Buddy",
  "version": "1.0",
  "description": "Copy URL, title, and description.",
  "manifest_version": 2,
  "browser_action": {
    "default_popup": "popup.html"
  },
  "permissions": ["tabs", "<all_urls>"]
}

getPagesSource.js

function copyToClipboard(document_root, str) {
  const el = document_root.createElement('textarea');
  el.value = str;
  document_root.body.appendChild(el);
  el.select();
  document_root.execCommand('copy');
  document_root.body.removeChild(el);
};

function DOMtoContent(document_root, win) {
    title = document_root.querySelector("h1").textContent;
    url = win.location.href
    description = document_root.querySelector("yt-formatted-string.content").textContent.split("\n»")[0];

    newline = "\r\n"

    text = title + newline + url + newline + newline + "Description:" + newline + newline + description;
    // DOES NOT WORK copyToClipboard(document_root, "aaaaa")
    return text;
}

chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoContent(document, window)
});

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:600px;height:700px">
<textarea id='message' style="width:100%; height:100%">Injecting Script....</textarea>
</body>
</html>

popup.js

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.value = request.source;
  }
});

function onWindowLoad() {

  var message = document.querySelector('#message');

  chrome.tabs.executeScript(null, {
    file: "getPagesSource.js"
  }, function() {
    // If you try and inject into an extensions page or the webstore/NTP you'll get an error
    if (chrome.runtime.lastError) {
      message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
    }
  });

}

window.onload = onWindowLoad;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment