How to find text-boxes from a Chrome extension

I’m making a Chrome extension and I need it to find any form text-boxes on the webpage.

I first tried doing it in my content script like:

document.getElementsByTag("text");

But it always returns undefined so I’m assuming it’s searching only my_app.html.

My first question is what function should I use: GetElmentsByTag, by name, by className, or with some other function?

My second question is which JavaScript file do I need to search? Other forums with similar problems said you need to access the DOM in another file like background or popup and then send it to the content script with a message and a listener.

Intercept like button on Facebook web app

I’m currently building a chrome extension and I’m trying to get it to be able to stop a like on Facebook from going through even after the like button has been clicked. In my content.js, I currently have the code:

document.querySelectorAll('a[data-testid="fb-ufi-likelink"]').forEach(function(element) {
    element.addEventListener('click', function() {
        var r = confirm("You clicked like");
            if (r == true) {
                alert("you clicked OK");
            } else {
                alert("you clicked Cancel")
            }           
    })
});

As of now, when the like button is clicked, a confirm box pops up but the like does not go through until “OK” or “Cancel” is clicked. The goal is to have the like go through when “OK” is clicked, and the like to not go through when “Cancel” is clicked on the confirm box. Is this implementation feasible? If so, how would I go about doing this?

Manipulating Extension popup’s DOM

I’m new at working on chrome extension and i’m looking for guidance.

At the moment, I’m trying to load data coming from an api call inside a dropdown menu within my extension’s popup.

While the data is coming through from the api, I can’t access the popup DOM. I hear that I should use sendMessage but I can’t find a proper explanation to why and how.

Here is what I have:

popup.html



    


    

p

popup.js

function load() {
  chrome.tabs.executeScript({
    file: 'load.js'
  }); 
}

load();

load.js

var xhr = new XMLHttpRequest();

    xhr.open("GET", "https://url/api/subject/list", false);
    xhr.send();

    var result = xhr.responseText;
    var obj = JSON.parse(result);
    console.log(obj); 

    var select = $('#subject');
    console.log(select); //undefined



    // for(index in obj) {
    //     select.options[select.options.length] = new Option(obj[index], index);
    // }
    console.log(rep);

manifest.json

{
"name": "-",
"description": "-",
"version": "0.1",
"permissions": [
    "tabs","",
    "https://url/*",
    "http://url/*"
    ],
"browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
    },
"web_accessible_resources": [
    "img/*.png",
    "reponses.json"
  ],
"content_scripts": [
    {
    "css": [ "style.css"],
    "matches": [
        "http://twitter.com/*",
        "https://twitter.com/*"
        ],
    "js": ["jquery.min.js", "content.js"]
    }
],


"background" : { "scripts": ["background.js", "popup.js"] },

"manifest_version": 2
}

chrome extension to monitor facebook wall

I’m trying to write chrome extension to track all posts that user see’s in current time in his wall (its mean that after every change in the wall i need to scan the dom and find the new data)
first i try to do it with event scroll, but i get to many messages. so I’m trying to do it with MutationObservers in that way:
Background.js:

chrome.extension.onMessage.addListener(  
  function(request, sender, sendResponse) {
    some logic
    }
  }
);

Content.js:

$(document).ready(function() {
  var target = $('.**need to figure out which tag to put here**').get(0);

  // Create an observer instance
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      **need to add some logic**
      chrome.extension.sendMessage({ data: document.all[0].outerHTML})

    });
  });

  // Configuration of the observer
  var config = { attributes:true, subtree: true };

  // Pass in the target node, as well as the observer options
  observer.observe(target, config);

});

I dont know after which tag to observe, i tried to look in facebook DOM and saw the only tag who update is the head, its not good enough cause i need the part who responsible on DOM changes.

thanks

DOM manipulation performance test puppeteer

i try to run performance testing with npm puppeteer to calculate how long it takes to append 500 element into my web page.
this is my code

const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto('http://localhost:2200/testing')
  const btnAddUser = await page.$('a#add-user')
  btnAddUser.click()
  const startTimeMs = new Date().getTime()

  await page.waitForSelector('div.user-item-499')
  const endTimeMs = new Date().getTime()

  console.log(`time to insert 500 user item is : ${endTimeMs - startTimeMs} ms`)
  await browser.close();
})();

and it works, but to be honest I still doubt it. is there any better way to do it?
test that I will do is in addition to adding elements, I will also remove the element and calculate the total time, so the page.waitForSelector will useless here…

can anyone solve this…
sorry for my bad english

Cant Append to Undefined Even When the Element Exists

This strange error keeps occurring where it says that it can’t append to an undefined node, even though its not null. I looked online and some say that its trying to append before the DOM finished loading, but this triggers after everything is loaded and the error persists.

Code of content script snippet:

function additionalcss() {
   var timelineselect = document.querySelector('#timeline');
   if (timelineselect != null) {   //it passes this so I know its not null
     console.log(timelineselect);  //this prints fine, and is defined
     const maindiv = document.createElement('div');
     maindiv.setAttribute('id', 'div-main');
     document.timelineselect.appendChild(maindiv);  //throws error here
     ReactDOM.render( , maindiv);
   }

chrome.storage dropping values

I was working on a chrome extension until I crossed a problem in which it seemed as if chrome.storage was dropping some values. I thought it may have been due to the logic in my program, so I stripped it all down to a bare-bones test (which is displayed here). I’m working with 3 files (aside from my manifest file), which are background.js, popup.html, and popup.js. I’ll post the files below along with their method descriptions. Feel free to skip reading the code of popup.js and popup.html, since I’m almost certain the problem is not within those two.

popup.js: If the user submits a form, it just adds the URL the user submitted and saves it to the database along with an array. It also makes sure that index 1 of the array is set to true to show that the user has added this URL. It then displays all other items in the database only if index 1 of their array is set to true.

    var urlBox = document.getElementById('URL');
    var subButton = document.getElementById('subButton');
    var urlBox = document.getElementById('URL');
    displayWatchList();

    subButton.onclick = function(e){
        e.preventDefault();
        var url = urlBox.value;
        chrome.storage.sync.get(url, function(data){
            var items = data[url];
            if(items){
                console.log('hi');
                items[1] = true;
                items[3] = 1;
                items[4] = 2;
                chrome.storage.sync.set({[url]: items});
                displayWatchList();
             } 
             else{
                 chrome.storage.sync.set({[url]: [0, true, false, 1, 2 ,0]});
                 displayWatchList();
             }
        });
    };

function displayWatchList(){
    chrome.storage.sync.get(null, function(data){
        for(var item in data){
            if(data[item][1]){
                var tableRow = document.createElement('tr');
                var tableUrl = document.createElement('td');
                var allowFor = document.createElement('td');
                var declineFor = document.createElement('td');
                var allowMins = document.createElement('input');
                var declineMins = document.createElement('input');

                allowMins.setAttribute('type', 'number');
                allowMins.setAttribute('class', 'numInput');
                declineMins.setAttribute('type', 'number');
                declineMins.setAttribute('class', 'numInput');

                allowFor.appendChild(allowMins);
                declineFor.appendChild(declineMins);
                allowFor.value = data[item][3];
                declineFor.value = data[item][4];
                tableUrl.textContent = item;
                tableRow.appendChild(tableUrl);
                tableRow.appendChild(allowFor);
                tableRow.appendChild(declineFor);
                watchTable.appendChild(tableRow);
            }
        }
    });
}

popup.html: just a simple form for the user to enter data into and a table to display the data.

    
    
        
            
    
    

        
Website Name Access Website For: Block Website For:

background.js: This is where the problem is. There are two functions.

logTime: For the purposes of this test, it simply gets ‘time’ from the database, and the gets ‘url’. If the url is in the database, just change the first element of items to 0. Otherwise, make a new item.

checkClose: It gets the current website the user accessed and sees if the second element is true. If so, check if the second element is true and print ‘hi’. Else change the last element to ‘yo’ and change the second element to true. the add this item to the database.

var items;
var mins;

chrome.runtime.onInstalled.addListener(function(){
    console.log("App Installed");
});

var web_list =[];

chrome.tabs.onUpdated.addListener(function(tabId, info, tab){

    if(info.status == 'complete'){
        var site = tab.url.match('^(([^:/?#]+):)?(//([^/?#]*))?')[4];
        checkClose(tab.id, site);
        logTime();

        chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
            web_list.push(tabs[0].url.match('^(([^:/?#]+):)?(//([^/?#]*))?')[4]); //get url of site and then extract host name
        });
    }
});

chrome.tabs.onActivated.addListener(function(){
    logTime();

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        web_list.push(tabs[0].url.match('^(([^:/?#]+):)?(//([^/?#]*))?')[4]); 
//get url of site and then extract host name
    });

});

function logTime(){
    if (web_list.length > 0){
        var url = web_list[web_list.length - 1];

        chrome.storage.sync.get('time', function(data){

            chrome.storage.sync.get(url, function(data){
                items = data[url];
                console.log(items);
            });

            if(items){
                item[0] = 0;
                chrome.storage.sync.set({[url]: items});
            }

            else{
                chrome.storage.sync.set({[url]: [0, false, false, 0, 0, 0]});
            }
        });
    }

}

function checkClose(id, site){

    chrome.storage.sync.get(site, function(data){
        var arr = data[site];
        console.log(site);
        console.log(arr);

        if(arr && arr[1]){

            if(arr[2]){
                console.log('jesus');
            }

            else{
                arr[5] = 'yo';
                arr[2] = true;
                chrome.storage.sync.set({[site]: arr});
            }

        }
    });
}

So after installing my extesnion, I add ‘www.google.ca’ in my popup. I then go to www.google.ca and the console prints ‘www.google.ca’ and [0, true, false, 1, 2, 0]. So far so good.

I then reload ‘www.google.ca’ and it prints ‘www.google.ca’ and [0, true, true, 1, 2, ‘yo’]. Even better.

I then reload it again and I get ‘www.google.ca’ and [0, true, false, 1, 2, 0]. I don’t get how this could happen. It literally just dropped the value!

I’d also like to state that this is my first chrome extension, and I’m fairly new to javascript, so it’s likely I’m just making a very stupid mistake. However, I just can’t seem to figure it out.

Thanks in advance.

Chrome Extension addEventListener null

I just started learning JS a few weeks ago and am trying to build a Chrome Extension. I’ve build a manifest.json, popup.html, popup.js, and content.js file.

When I try running the background page console on Chrome to see if the popup.js is working I keep getting the error:

Uncaught TypeError: Cannot read property 'addEventListener' of null
at popup.js:8

I’ve tried moving the script in the html to the bottom of the body, but it still ends in an error and have tried implementing:

document.addEventListener('DOMContentLoaded', function () {
    //   My code here.. ( Your code here  )
    }); 

in my popup.js and the windows.onload method, but still haven’t been able to get rid of the error.

If someone could please point out any errors in my code and tell me what is wrong I would really appreciate it. Thanks

POPUP HTML




    Like IG Links




    

Paste Links Below







CONTENT JS

console.log('CHROME');

POPUP JS

console.log('background running');

function loadUrls() {
console.log("123");
}

var startbutton = document.getElementById("start");
startbutton.addEventListener('click', loadUrls);    

MANIFEST JSON

{ 
"manifest_version": 2,      
"name": "Like IG Links",
"version": "1.0",    
"description": "Like IG Links",

"content_scripts": [
    {
        "matches": [
            ""
        ],
        "js": ["content.js"]
    }    
],

"background": {
    "scripts": ["popup.js"]
    },

"browser_action": {
"default_icon": "icon.png",  
"default_popup": "popup.html"                 
},

"permissions": ["tabs", "storage", "activeTab"]
}

Making a Chrome Extension with React to Look at DOM Changes

I was thinking of using React to develop a chrome extension. This app would need to check for any DOM changes on the current web page the user is on.

I have always used react to check DOM updates within the react app itself, is it possible to check the DOM of web pages with a react chrome extension?

Chrome Extension Inject HTML on YouTube Page [duplicate]

This question already has an answer here:

I am creating a Chrome Extension that will inject HTML on top of the related videos bar of a YouTube video.

This is the desired effect of the plugin.

Here is the manifest.json:

{
  // Required
  "manifest_version": 2,

  // App
  "name": "...",
  "version": "...",
  "author": "...",
  "description": "...",

  "content_scripts": [
    {
      "run_at": "document_idle",
      "matches": ["*://www.youtube.com/watch?v=*"],
      "js": ["jquery-min-3.3.1.js", "inject.js"]
    }
  ]

}

And here is inject.js:

$(document).ready(function(){
  $('#related').prepend('

This was injected throught jQuery.

'); });

When the extension is loaded into Chrome and a YouTube video page is loaded, the script seems to work for a second. The h1 in injected at the top of the #related bar until related video thumbnails start to load. Then the injected h1 quickly is pushed to the bottom as each new thumbnail loads.

I’m guessing this has something to do with YouTube using AJAX to load content. Is there a way to wait until all AJAX has been loaded before injecting HTML?