0

I've been trying to write some JavaScript for a Chrome extension that can read elements by class name from a website which I don't own. For example, if I inspect this website there is a body tag with class="x" in it, this sometimes updates to class="y". All I need to do is be able to read this value.

So far I have tried using:

    var x = document.getElementsByClassName("x");
    if (x.length > 0) window.alert("Alert");  

This works when I have this in script tags beneath my own HTML. However I have no idea how to do this for an external website. Ideally I use a solution using vanilla JS but please also let me know if I will have to use libraries to do this.

  • 1
    Have you looked into browser extensions like Greasemonkey / Tampermonkey that let you set user scripts to run on every page? Seems like that would be the easiest route for someone with no extension-building experience. – IceMetalPunk Sep 20 '19 at 15:47
  • How about this: https://stackoverflow.com/a/50812705/2928853 – jrook Sep 20 '19 at 15:51

1 Answers1

0

You need to use "content scripts" to run your code in a context of web page.

Take a look at Google's doc here - https://developer.chrome.com/extensions/content_scripts

Also you mentioned about possibility of changes, if you need to watch if object changes, you can use Mutation Observer API.

Take a look at Mozilla's doc here - https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Zekfad
  • 189
  • 12