vdegenne
vdegenne

Reputation: 13270

Why can't my chrome extension content script have access to a page element's property?

I am trying to make a chrome extension that will provide ctrl+left arrow and ctrl+right arrow to backward or forward the YouTube video by 2 seconds. Here is my script :

const player = document.querySelector('ytd-player').getPlayer();
const seconds = 2;
window.addEventListener('keydown', function (e) {
  if (e.ctrlKey) {
    if (e.keyCode === 37) {
      player.seekToStreamTime(player.getCurrentTime() - seconds)
    }
    else if (e.keyCode === 39) {
      player.seekToStreamTime(player.getCurrentTime() + seconds)
    }
  }
})
console.log('youtube-seconds extension loaded.');

The script is working if I run directly from the chrome devTools but if I make an extension with the same code it doesn't work.

After investigating the code I noticed the issue comes from getPlayer function.
The document.querySelector('ytd-player') works well if I console.log but getPlayer returns nothing from the script. How would one explain that ? and how can I make this work ? am I missing a permission or something ?

Upvotes: 1

Views: 1553

Answers (1)

Radu Diță
Radu Diță

Reputation: 14171

Content scripts share the same DOM as the original page, but have different JS contexts.

This means that you can't access JS that's on the original page.

What you can do to overcome this is to inject a JS script in the original page. Considering you have access to the same DOM you can use document.createElement('script') to create a script and populate it with your JS code.

Then you can use window.postMessage to send messages to and from your content and injected script.

Upvotes: 5

Related Questions