Reputation: 13270
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
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