Building extension for style change with key press

I am building a Chrome Extension in which I want to edit the style of the web pages I visit by using keypress. I am trying to target all style elements (I tried it now by using *).

I found multiple parts of code online, all of which don’t seem to work:

$("*").keypress(function(event){

if(event.which==65 {

$("*").css("background-color", "white");
    }
}

Or:

$( "body" ).keydown(function( event) {

if (event.which == 65  {

$("body").css("color","white");
  }
});

Or:

function changeColor() {

  var color = document.getElementById("color").value;
  document.body.style.background = color;
}
document.querySelector('#color').addEventListener('keydown', function(e) {
  if (e.keyCode === 65) { // enter key
    changeColor("red");
  }
});

The ideal changes would be:

Key press a > change background to white

Key press b > change font to helvetica

Key press c > hide all images

Key press d > hide all text

At the moment I don’t get any results at all (while changing the background in css immediately works).

Reading DOM content from a background script?

Let’s say there are two websites: x.com and y.com. Here is what I have done so far:

  1. When a button is clicked on x.com, send a message to a background script.
  2. The background script opens a new tab to y.com.

However, now that the tab to y.com has opened, how can I read from the DOM from y.com and use that info in the content script that is running on x.com?


Here is my code so far:

content.js (Content script that runs for x.com)

var btn = document.querySelector('my-btn')

// Send message when btn is clicked
btn.addEventListener('click', message) 

function message() {
  chrome.runtime.sendMessage({ message: 'Get Y data' }, null, function() {
    // I want to use data from `y.com` here somehow
  })
}

background.js

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) {
  if (response.message !== 'Get Y data') {
    return
  }

  var url = '...'

  chrome.tabs.create({ active: true, url: url }, function (tab) {
    // How do I read DOM from this new `tab` and send it back to content script?
  })
})

Get Chrome Extension to work on different tab?

I’m pretty new to programming chrome extensions. The one that I have programmed works as I would like it, however you need to be clicked into the specific tab in order for it to work. For example, I can’t just have the site open while perusing the internet in a separate window.

The webpage that this is for is my company’s service check page where different teams from the company post issues that they’ve had for others to see and work on. My extension reads this page for any issues that have gone unnoticed for more than ten minutes and notifies the user using a toast popup. I think it is the active tab that makes it so the extension runs on whichever tab is currently clicked into, but I am not sure. Is there anyway I can make it so this extension runs without having to be in the tab?

Here is the code I have, any suggestions for how the extension is set up are welcome as well:

manifest.json

{
  "manifest_version": 2,

  "name": "Nagios Notifications",
  "description": "This extension allows a notification to be sent when a Nagios check reaches 10 minutes duration",
  "version": "1.0",
  "icons": { "16": "img/icon_16.png",
              "48": "img/icon_48.png",
              "128": "img/icon_128.png"},
  "browser_action": {
    "default_icon": "img/icon.png",
    "default_popup": "popup.html",
    "default_title": "Click to show notifications!"
  },
  "content_scripts": [
    {
      "matches": ["http://eotnagios/nagios/*"],
      "js": ["js/contentscript.js", "js/jquery-3.2.0.min.js", "js/jquery-toast-plugin-master/src/jquery.toast.js"],
      "css": ["js/jquery-toast-plugin-master/src/jquery.toast.css"],
      "all_frames": true,
      "run_at" : "document_start"
    }
  ],
  "permissions": [
    "activeTab",
    "storage",
    "background",
    "notifications",
    "tabs",
    "webNavigation",
    "http://eotnagios/nagios/*"
  ],
  "web_accessible_resources": [
    "img/*.png",
    "css/*.css",
    "js/*.js"
  ],
  "background": {
    "scripts": ["js/jquery-3.2.0.min.js", "js/jquery-toast-plugin-master/src/jquery.toast.js", "js/background.js"]
  }
}

background.js

//When frame updates
chrome.webNavigation.onReferenceFragmentUpdated.addListener(function () {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
  chrome.tabs.sendMessage(tabs[0].id, {subject: "checkTable"}, function(response) {
    console.log(response);
    })
  })
})

//On page load
chrome.webNavigation.onCompleted.addListener(function () {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
  chrome.tabs.sendMessage(tabs[0].id, {subject: "checkTable"}, function(response) {
    console.log(response);
    })
  })
})

//When extension is clicked
chrome.browserAction.onClicked.addListener(function () {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
  chrome.tabs.sendMessage(tabs[0].id, {subject: "checkTable"}, function(response) {
    console.log(response);
    })
  })
})

//When page is clicked
chrome.tabs.onActivated.addListener(function () {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
  chrome.tabs.sendMessage(tabs[0].id, {subject: "checkTable"}, function(response) {
    console.log(response);
    })
  })
})

contentscript.js:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.subject == "checkTable" || request.subject == "notifications") {
      var table = document.getElementsByClassName("status")[1];
      var durations = [];
      if (typeof table !== 'undefined'){
      for (var i = 0, row; row = table.rows[i]; i++) {
        var tableRow = {};
        //rows
        for (var j = 0, col; col = row.cells[j]; j++) {
          if (j == 4 && i != 0) {
          tableRow["duration"] = col.innerHTML;
          }
          else if (j == 1 && i != 0) {
            tableRow["service"] = col.innerHTML;
          }
        }
        if (Object.keys(tableRow).length == 2){
          durations.push(tableRow);
        }
      }
      for (var k = 0; k < durations.length; k++) {
        var acknowledged = "no";
        var time = durations[k]["duration"].split(" ")
        for (var item = 0; item < time.length; item++) {
          if (time[item].slice(-1) == "h") {
            var hours = time[item];
            if (hours.length == 2) {
              hours = parseInt(hours.substr(0, 1));
            }
            else if (hours.length == 3) {
              hours = parseInt(hours.substr(0, 2));
            }
          }
          else if (time[item].slice(-1) == "m") {
            var minutes = time[item];
            if (minutes.length == 2) {
              minutes = parseInt(minutes.substr(0, 1));
            }
            else if (minutes.length == 3) {
              minutes = parseInt(minutes.substr(0, 2));
            }

            var hourMinutes = hours * 60;
            minutes += hourMinutes;

            if (minutes > 10) {
              var check = durations[k]["service"];
              check = check.split(" ");
              for (var x = 0; x < check.length; x++){
                if (check[x].substr(0, 4) == "href") {
                  var line = check[x].split(";");
                  var host = line[1];
                  host = host.split("=")[1];
                  host = host.split("&")[0];
                  line = line[2];
                  line = line.split("#");
                  line = line[0].split(">")
                  line = line[0].split("=");
                  line = line[1].split(""");
                  var service = line[0];
                }
                else if (check[x].substr(0, 3) == "src") {
                  var line = check[x].split("/");
                  line = line[3].split(""");
                  line = line[0];
                  if (line == "ack.gif") {
                    acknowledged = "yes";
                  }}}}
              }
            }

            var serviceCheck = {"duration" : minutes, "service" : service, "host" : host, "acknowledged" : acknowledged};
            if (minutes > 10) {
              var toastColor;
              if (minutes <= 30) {
                toastColor = "orange";
              }
              else if (30 < minutes && minutes <= 60) {
                toastColor = "orangered";
              }
              else if (60 < minutes && minutes <= 120) {
                toastColor = "darkRed";
              }
              else {
                toastColor = "red";
              }

              //var notified = notifications(serviceCheck["host"], serviceCheck["service"]);
              if (serviceCheck["acknowledged"] == "no"){
            $.toast({
              text: "Minutes passed: " + minutes + " Service: " + service + " Host: " + host + " Acknowledged: " + acknowledged,
              hideAfter: false,
              position: 'bottom-right',
              bgColor: toastColor,
              textColor: 'white'
              });
            }
            }
              sendResponse(serviceCheck);
          }
        }
        }
      }
    )

chrome extension capture fullscreen hidden tab

Description

I want to make chrome extension a next behaviour: it makes screenshot of custom tab (or window) which can’t be focused by user (this tab (or window) can be minimized always or it can be hidden somewhere) and it must be able to change location.href

What needs

I need to make him one of two engines:

  1. Make screenshots of non-current tab even if it’s minimized
  2. Make a hidden tab (like background) which can be screenshoted in fullsize

What I have now

Now I’m using chrome.tabs.captureVisibleTab to take a screenshot of custom window created when extension was initialized and if user tries to focus this window – I change focus on last focused window by chrome.windows.update

Problem

It works fine but then all windows closed (except custom created) when extension needs to hide this window too. But I can’t minimize it (even if I can then I wouldn’t be able to take a screenshot of this window)

Question

Any ideas how to make the one of behaviours of extension that I want?
Big thanks for answers!

Accessing website variables with injected script through background.js

I am building a Chrome Extension and when clicked on the toolbar icon, I am executing background.js, and in background.js I am running execute script. Like this:

chrome.tabs.executeScript(null, { file: "libs/jquery.min.js" }, function() {
    chrome.tabs.executeScript(null, { file: "scripts/myScript.js" })
});

In myScript.js, I can confirm that it has executed jQuery and running my script too.


myScript.js:

console.log('test');

$(document).ready(function() {
   console.log('jQuery test');
})

They both work


At this point, I am trying to achieve a variable that is inside the web page (not written by me); let’s say it is var helloWorld = "the content".

If I try in the console (dev tools), console.log(helloWorld), it works. However, if I try in myScript.js, it says:

$(document).ready(function() {
    console.log(helloWorld)

    setTimeout(function() {
       console.log(helloWorld)
    }, 1500)
})

Uncaught ReferenceError: helloWorld is not defined


I have seen some workaround for content script approach, but I couldn’t make it work for the executeScript approach. How can I access the helloWorld variable inside myScript.js?