I am building a chrome extension that needs to be able to open Spotify in an inactive tab and start playing music automatically from there.
So I open the new tab.
chrome.tabs.create({
pinned: true,
active: false,
url: 'https://open.spotify.com/'
},(tab) => {
chrome.scripting.executeScript({
target: { tabId: tab.id, allFrames: true },
files: ["scripts/spotify.js"]
});
});
And then in my script I wait until play button is loaded in the dom and then I click it.
let playButton = document.querySelector('[data-testid="control-button-playpause"]');
playButton.click();
This works fine if the user already has spotify open in a different tab or they have the spotify desktop app open since it will play from either one of those after hitting the play button in the inactive tab.
But the issue is, if they don’t already have spotify open somewhere, spotify will get an error where it says that it is playing and the progress bar is moving, but no audio. I also get this error below in the console, but not completely sure it is related.
Uncaught (in promise) PlayerAPIClientError: Command didn’t receive an acknowledgement within 30000ms
at web-player.b540622e.js:1:738440
at o (vendor~web-player.9b9cbfd8.js:1:163454)
If I view the new spotify tab my chrome extension opened before my script has a chance to hit the play button, it will work fine. So I think the issue is related to spotify holding off completely loading until being viewed.
So I tried these two different chrome extensions (one and two) to disable the page visibility API in case that was it, but it still wouldn’t load completely until I viewed the tab.
I tried putting these into my injected script to try to trick the spotify page into thinking the user was there, but they didn’t work either.
// Simulate visibility change
Object.defineProperty(document, 'visibilityState', {
get: () => 'visible'
});
document.dispatchEvent(new Event('visibilitychange'));
// Simulate pageshow
window.dispatchEvent(new Event('pageshow'));
// Simulate focus
window.dispatchEvent(new Event('focus'));
// Simulate DOMContentLoaded
document.dispatchEvent(new Event('DOMContentLoaded'));
// Simulate resize
window.dispatchEvent(new Event('resize'));
// Simulate mouse movement
const mouseMoveEvent = new MouseEvent('mousemove', {
view: window,
bubbles: true,
cancelable: true
});
document.dispatchEvent(mouseMoveEvent);
// Simulate scroll
window.scrollTo(0, 100);
I also have my energy and memory savers turned off in my chrome settings.
Anybody have any other ideas to get the page to load completely without viewing it or any other ways around this issue? I don’t want to have to ask user to have spotify opened somewhere else first and it is vital to the user experience that this tab is opened in an active state, even if it automatically switches them back.