Chrome extension - page update twice then removed on YouTube - javascript

I want to make a small extension that injects a simple html into a YouTube page right under the video. It works fine if I simple visiting a youtube url. However if I choose a video from youtube offers then my html code is injected twice but removed. I can see that it to appear and then disappear almost immediately.
My code is:
background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if ( changeInfo.status == 'complete' && tab.status == 'complete' && tab.url != undefined ) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {method: "reDraw"}, function(response) {
console.log("Injection ready!");
});
});
}
});
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.method == "reDraw") {
$.get(chrome.extension.getURL('/mytest.html'), function(data) {
$(data).insertAfter('#placeholder-player');
});
}
}
);

chrome.tabs.onUpdated will also fire for iframes, and for youtube, there are many iframes will trigger this event, besides that, youtube doesn't reload the page when you go from one video to another. For more details about youtube issue, you could take a look at these threads:
https://bugs.chromium.org/p/chromium/issues/detail?id=165854
Chrome webNavigation.onComplete not working?
chrome extension chome.tabs.onUpdate running twice?
So my recommendation would be using chrome.webNavigation api, and combining webNavigation.onCompleted with webNavigation.onHistoryStateUpdated, sample code would look like the following
Considering you are detecting youtube video page, I would suggest you used chrome.webNavigation.onHistoryStateUpdated
// To handle youtube video page
chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
if(details.frameId === 0) {
// Fires only when details.url === currentTab.url
chrome.tabs.get(details.tabId, function(tab) {
if(tab.url === details.url) {
console.log("onHistoryStateUpdated");
}
});
}
});

Here is a way to only fire one time using chrome.webNavigation.onHistoryStateUpdated
// background.js
'use strict';
console.log('QboAudit Background Script');
chrome.runtime.onInstalled.addListener(details => {
console.log('QboAudit previousVersion', details.previousVersion);
})
chrome.webNavigation.onHistoryStateUpdated.addListener( (details) => {
console.log('QboAudit Page uses History API and we heard a pushSate/replaceState.')
if(typeof chrome._LAST_RUN === 'undefined' || notRunWithinTheLastSecond(details.timeStamp)){
chrome._LAST_RUN = details.timeStamp
chrome.tabs.getSelected(null, function (tab) {
if(tab.url.match(/.*\/app\/auditlog$/)){
chrome.tabs.sendRequest(tab.id, 'runQboAuditLog')
}
})
}
})
const notRunWithinTheLastSecond = (dt) => {
const diff = dt - chrome._LAST_RUN
if (diff < 1000){
return false
} else {
return true
}
}
In short you make a global var chrome._LAST_RUN to track if this event has already fired less than a second ago.
// contentscript.js
chrome.extension.onRequest.addListener((request, sender, sendResponse) => {
//console.log('request', request)
if (request == 'runQboAuditLog')
new QboAuditLog()
});

I guess youTube is using Ajax calls on some pages to load things, so your code is being replaced with the Ajax response.
Use a setTimeout() function to check after a few seconds if your code is on the page, if it's not, add it again.

Related

JavaScript callback / async problem? Background script of Chrome Extension stops function before finishing

I am trying to create a small crawler as a chrome extension. How it works is:
Open new window or tab.
Perform a search for Google / Google News / YouTube with given keywords.
Store information of the results in a small database
I first created and tested the functions with a popup.html. There it works perfectly.You click on a button and all pages are visited and the results are stored in a database. But I want to start the program without clicking anything first. That's why I migrated it to background.js. There it also works, but only if the Service Worker / DevTool console is open. Only then it runs completely.
I would be grateful for any helpful answer.
const keywords = [
"Keyword1",
"Keyword2",
// ...
"Keyword13"
];
chrome.runtime.onStartup.addListener(() => {
chrome.tabs.onUpdated.addListener(loadingWindow);
openWindow();
});
// Opens new Window or Tab with the correct URL
function openWindow() {
chrome.tabs.onUpdated.addListener(loadingWindow);
if (runs == 0) {
chrome.windows.create({ url: getUrl(keywords[runs]), type: "normal" }, newWindow => {
window_id = newWindow.id;
});
} else {
chrome.tabs.update(tab_id, { url: getUrl(keywords[runs]) });
}
}
// Wait to load the new tab
function loadingWindow(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete' && tab.status == 'complete' && tab.windowId == window_id) {
tab_id = tabId;
console.log(tab.windowId);
chrome.tabs.onUpdated.removeListener(loadingWindow);
chrome.tabs.sendMessage(tab.id, { text: source }, doStuffWithDom);
}
};
// Get information from content script -> payload and then send to database
function doStuffWithDom(domContent) {
let payload = {... }
var data = new FormData();
data.append("json", JSON.stringify(payload));
fetch(".../store.php", { method: "POST", body: data });
crawlDone();
}
// open new window / tab or close the open window
function crawlDone() {
runs++;
if (runs < keywords.length) {
openWindow();
} else if (runs == keywords.length) {
chrome.windows.remove(window_id);
}
};
I switched to Manifest version 2. Then I could include the Background.js via the Background.html, which also runs to the end.

chrome.runtime.onMessage listener is never fired

I'm trying to set a badge text specific for each tab in Chrome.
I've followed along with this answer https://stackoverflow.com/a/32168534/8126260 to do so, though the chrome.runtime.onMessage event handler is never being fired.
// tab specific badges https://stackoverflow.com/questions/32168449/how-can-i-get-different-badge-value-for-every-tab-on-chrome
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
console.log('runtime message');
if (message.badgeText) {
console.log('runtime message with badge text');
chrome.tabs.get(sender.tab.id, function(tab) {
if (chrome.runtime.lastError) {
return; // the prerendered tab has been nuked, happens in omnibox search
}
if (tab.index >= 0) { // tab is visible
chrome.browserAction.setBadgeText({tabId:tab.id, text:message.badgeText});
console.log('set message');
} else { // prerendered tab, invisible yet, happens quite rarely
var tabId = sender.tab.id, text = message.badgeText;
chrome.webNavigation.onCommitted.addListener(function update(details) {
if (details.tabId == tabId) {
chrome.browserAction.setBadgeText({tabId: tabId, text: text});
chrome.webNavigation.onCommitted.removeListener(update);
}
});
}
});
}
});
// block outgoing requests for help widgets
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
//send message
console.log('send message');
chrome.runtime.sendMessage({badgeText: "HELP"});
if (isDisabled) {
return { cancel: false } // this should return from the function (details) level
} else {
return { cancel: true }
}
},
{urls: [
"a bunch of urls irrelevant to this question"
]},
["blocking"]);
(the entire source code is on https://github.com/bcye/Hello-Goodbye)
Looking into the console of my background script, send message appears, meaning that chrome.runtime.sendMessage({badgeText: "HELP"}); should have been executed.
None of the console.log statements in the onMessage listener get executed though.
Solved it, as #wOxxOm said this is impossible.
Though webRequest passes a tabId in the details dictionary.
This can be used to replicate that.

Chrome extension message passing & order of execution [duplicate]

This question already has an answer here:
Clipboard Copy / Paste on Content script (Chrome Extension)
(1 answer)
Closed 6 years ago.
Quick summary
The code below is a file called popup.js. It listens for a click, and sends a message to background.js. Background.js executes another script, and a variable is created.
I somehow need to pass this variable back to popup.js, and continue within the userHasClicked function. The way it is now the response I get is "undefined", and there's nowhere to go from there.
var theParent = document.querySelector("#MENY");
theParent.addEventListener("click", userHasClicked, false);
function userHasClicked(e) {
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
chrome.runtime.sendMessage({type: "ResponseType", directive: clickedItem}, function(response) {
console.log(response);
this.close();
});
};
e.stopPropagation();
}
Routine:
User clicks on an option in popup.html
Event("click") -> sendmessage("type of click")
background.js listens for the message, and executes content.js
content.js creates the variable and can send it back to anyone who listens.
The problem:
The variable must come as a response argument to step 2 (within eventloop)
Save the response as variable.
document.execCommand("copy").
Done
This code below is the relevant part of background.js.
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
switch (request.type) {
case "ResponseType":
var LoggType = request.directive;
console.log(LoggType)
chrome.tabs.executeScript(null, {
code: 'var LoggType = "'+LoggType+'";'
}, function() {
chrome.tabs.executeScript(null, {file:"content.js"});
});
chrome.runtime.onMessage.addListener(function(req, snd, sndRes) {
if (req.type = "LogIsGenerated") {
var Logg = req.directive;
console.log(Logg);
} sndRes({});
});
if (typeof Logg !== "undefined") {
alert("Feedback from content.js received");
sendResponse({type: "FinalVar", directive: Logg});
}
else {
alert("No feedback received");
sendResponse({});
};
break};
return true;
}
);
content.js ends with this line.
chrome.extension.sendMessage({type: "LogIsGenerated", directive: Logg});
Logg is the variable containing the text string I want to add to the clipboard.
At the moment this the code below alerts for No feedback received.
chrome.runtime.onMessage.addListener(function(req, snd, sndRes) {
if (req.type = "LogIsGenerated") {
var Logg = req.directive;
console.log(Logg);
} sndRes({});
});
if (typeof Logg !== "undefined") {
alert("Feedback from content.js received");
sendResponse({type: "FinalVar", directive: Logg});
}
else {
alert("No feedback received");
sendResponse({});
};
Rob W presented a solution here: Background script can write to clipboard in a very simple manner
Worked excellently.

Inconsistent/Delayed HTML5 Desktop Push Notifications on Chrome

I'm writing a chat webapp that needs to be able to trigger desktop push notifications through the notifications API: https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API
Unfortunately, it seems that the notifications don't show up until I flush it all out by making another notification with this fiddle: https://jsfiddle.net/yoshi6jp/Umc9A/
This is the code that I am using:
function triggerDesktopNotification() {
function makeNotification() {
var notification = new Notification('AppName', {
body: 'You have a new message!',
icon: '/favicon.ico',
});
notification.onclick = () => {
notification.close();
};
}
if (Notification.permission === 'granted') {
makeNotification();
}
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
if (permission === 'granted') {
makeNotification();
}
});
}
}
I can confirm that the code is executing properly by placing console.log() immediately after the new Notification call. Interestingly, if I put an alert() there instead, the notification shows up when I see the alert box (after navigating back into my tab).
If I understood you right ;
Alert interrupts program stack where it placed i think.Why dont you try to fire it async with setTimeout function like that ?
setTimeout( function(){
alert("asd");
})
edited js fiddle here

Cannot send message to content script properly

I'm so close to finishing my Chrome extension. I have one or two things to do. One of them is sending a message from the content script to the background script. I wrote the following, but it doesn't quite what I want.
content.js
var a=document.getElementsByTagName('a');
for (i=0,len=a.length;i<len;i++) {
a[i].addEventListener('contextmenu', function() {
var linkTitle = this.getAttribute('title').trim();
var linkUrl = this.getAttribute('href');
if ((linkTitle != null) && (linkTitle.length > 0)) {
chrome.extension.sendMessage({action:'bookmarkLink', 'title':linkTitle, 'url': linkUrl}, function(msg) {
alert('Messages sent: '+action+' and '+linkTitle+' also '+linkUrl);
});
}
});
};
background.js
chrome.contextMenus.create({'title': 'Add to mySU bookmarks', 'contexts': ['link'], 'onclick': mySUBookmarkLink});
function mySUBookmarkLink(info, tab) {
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action == 'bookmarkLink') {
chrome.storage.sync.set({'title': msg.linkTitle, 'url': msg.linkUrl}, function(msg) {
alert('Saved '+msg.linkTitle+' to bookmarks');
});
}
});
};
My problems are:
In the first code block, it alerts Saved undefined to bookmarks as soon as I right click on the link, while as I understand it should only send a message on right click and the second code block should alert Saved to bookmarks when I click on the context menu. What am I missing or doing wrong?
I may not have used parameters correctly (I am fairly new to extension development and Javascript in general). Do the above look okay?
Thank you in advance,
K.
It's chrome.runtime.sendMessage and chrome.runtime.onMessage rather than chrome.extension.
There used to be chrome.extension.sendRequest and chrome.extension.onRequest which have been deprecated in favor of the chrome.runtime API methods mentioned above.
See Chrome Extensions - Message Passing
it's JSON-serializable messaging, where first pair is for recognition, and then followed by pairs of
key: value.
You pull the value from received message by calling it's key.
is should be:
alert('Saved '+msg.title+' to bookmarks');
or even better:
function mySUBookmarkLink(info, tab) {
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action == 'bookmarkLink') {
var receivedValue = msg.title; //pull it out first, for better overview
chrome.storage.sync.set({'title': msg.title, 'url': msg.url}, function(msg) {
alert('Saved '+receivedValue+' to bookmarks');
});
}
});
};

Categories

Resources