Content scripts not trapping chrome.tabs.onUpdate - google-chrome-extension

I am developing a Google Chrome Extension. I want to get the contents(text only) of the active tab. I am sure that Content scripts will help me find what I am looking for.
But I am stuck in the below scenario:
If I run my chrome.tabs.onUpdated.addListener(function(){ in my background.js, I am able to achieve other tasks, say ajax post etc. But if I include document.body.innerHTML in that chrome.tabs.onUpdated.addListener(function(){, to get the contents of the opened tab, it is alerting the contents of my background.html and NOT the contents of the tab which is opened in the browser.
If I paste the chrome.tabs.onUpdated.addListener(function(){ in my content scripts, I am not able to trap the tab update.
Can I know where I am going wrong?

Try like this:
// In background.js
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status === 'complete') {
chrome.tabs.sendMessage(tabId, {type: 'getDoc'}, function (doc) {
console.log(doc);
});
}
});
// In content_scripts.js
chrome.extension.onMessage.addListener(function(request, sender, response) {
if (request.type === 'getDoc') {
response(document.body.innerHTML);
}
return true;
});

Related

"Scroll to Text" not working in Extension

I've built a Chrome Extension (pop-up) and one of the primary functions is opening different web pages when the user clicks on a link. Sometimes I want to focus on specific text on the new page so I'm trying to use the "scroll to text fragment" feature through my extension.
Unfortunately, when the page loads, this feature (scroll to text) fails. I have tested the exact same link manually and it works fine, but when I inject this link into the browser through my extension, nothing happens except the page loading as normal.
Here are a few more details that might help:
The problem I'm having is using Chrome.tabs.update() which is triggered by a user clicking a link in my popup
We are using manifest v2 not v3
The exact command from the popup javascript is (not tab id as it defaults to current tab):
chrome.tabs.update({ url: "http://example.com/#:~:text=example", })
In the manifest, we do not have the "tabs" permission.
Is there a special permission needed to use this feature in my extension? Is there something I need to do in my extension code to make this work as expected? I'm at a loss for next steps.
This is the exact feature I'm referring to: https://chromestatus.com/feature/4733392803332096
And here's an example of the feature in action:
https://chromestatus.com/feature/4733392803332096#:~:text=Motivation-,Navigating%20to%20a%20URL,-today%20will%20load
Any help would be greatly appreciated. Thank you.
There's no special permission so apparently it's a bug in Chrome: crbug.com/1241508
A simple workaround is to use chrome.tabs.create and close the original tab, but it flickers in the tab strip and loses the tab's back/forward history, sessionStorage, and so on.
function navigate(url) {
chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => {
chrome.tabs.remove(tab.id);
chrome.tabs.create({ url, index: tab.index });
});
}
Another workaround is to set the hash part of the URL in the content script, but it requires host permissions for the navigated site in manifest.json like *://example.com/
async function navigate(url) {
if (await setUrlInContentScript(url)) {
return true;
}
const [base, hash] = url.split('#');
await onTabReceivedUrl(await new Promise(resolve => {
chrome.tabs.update({ url: base }, resolve);
}));
return setUrlInContentScript('#' + hash, 'hash');
function setUrlInContentScript(url, part = 'href') {
return new Promise(resolve => {
chrome.tabs.executeScript({
code: `location.${part}=${JSON.stringify(url)}`,
runAt: 'document_start',
}, () => resolve(!chrome.runtime.lastError));
});
}
function onTabReceivedUrl(tab) {
return new Promise(resolve => {
chrome.tabs.onUpdated.addListener(function onUpdated(tabId, info) {
if (tabId === tab.id && info.url) {
chrome.tabs.onUpdated.removeListener(onUpdated);
resolve();
}
});
});
}
}
In my case I discovered, that one of the characters ~ was encoded. You need the real characters to get Scroll to Text working.

Chrome extension detect Google search refresh

How can my content script detect a refresh of Google's search?
I believe it is an AJAX reload of the page and not a "real" refresh, so my events won't detect the refresh.
Is it possible to detect it somehow in both a Google Chrome extension and a Firefox WebExtensions add-on?
Google search is a dynamically updated page. Several well-known methods exist to detect an update: MutationObserver, timer-based approach (see waitForKeyElements wrapper), and an event used by the site like pjax:end on GitHub.
Luckily, Google Search in Chrome browser uses message event, so here's our content script:
window.addEventListener('message', function onMessage(e) {
// console.log(e);
if (typeof e.data === 'object' && e.data.type === 'sr') {
onSearchUpdated();
}
});
function onSearchUpdated() {
document.getElementById('resultStats').style.backgroundColor = 'yellow';
}
This method relies on an undocumented site feature which doesn't work in Firefox, for example.
A more reliable crossbrowser method available to Chrome extensions and WebExtensions is to monitor page url changes because Google Search results page always updates its URL hash part. We'll need a background/event page, chrome.tabs.onUpdated listener, and messaging:
background.js
var rxGoogleSearch = /^https?:\/\/(www\.)?google\.(com|\w\w(\.\w\w)?)\/.*?[?#&]q=/;
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (rxGoogleSearch.test(changeInfo.url)) {
chrome.tabs.sendMessage(tabId, 'url-update');
}
});
content.js
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg === 'url-update') {
onSearchUpdated();
}
});
function onSearchUpdated() {
document.getElementById('resultStats').style.backgroundColor = 'yellow';
}
manifest.json: background/event page and content script declarations, "tabs" permission.

message passing happens twice if "run_at" : "document_start" is used in chrome extension

In my extension, I am passing a message from background.js to contentScript.js.
The issue is that when I use
"run_at" : "document_start"
in my manifest.json, the message from background.js to contentScript.js is called twice and sometimes even more than that.
Message passing more than once is a bit expensive in my case as I'm sending a call to server and the processing the same values at the server multiple times is expensive.
background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
chrome.tabs.sendMessage(tab.id, {type: "get-url", url: tab.url});
});
contentScript.js
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
switch(message.type) {
case "get-url" : someFunction(message.url);
break;
// other cases
}
});
Is there a way to solve this?
chrome.tabs.onUpdated is called multiple times in the tab-update cycle (e.g. when the tab starts loading the new page, when the tab completes loading the new page, when the favicon is fetched etc).
The best option is to checj for when the tab has completed loading:
chrome.tabs.onUpdated.addListener(function (tabId, info, tab) {
if (info.status === 'complete') {
/* Now it is safe to send the message */
chrome.tabs.sendMessage(tabId, {
type: 'get-url',
url: tab.url
});
}
});
BTW, when injecting programmatically (not in manifest.json), the property's name is runAt, not run_at (docs).

chrome extension messaging from background to content script gives :Port error: Could not establish connection. Receiving end does not exist [duplicate]

For my Chrome extension, I am attempting to post selected text to a PHP webpage. A solved question on this website (Chrome Extension: how to capture selected text and send to a web service) has helped me a lot in achieving this, but I want a different way of posting the text.
Instead of XMLHttpRequest as mentioned there, I want to send a hidden JS form from the content script. This method allows me to view or change the text before importing it to the database.
The problem is to get the trigger from the background to the content script. I already have a message the other way, so using the function(response) is desired. However, outside the “sendMessage”, I can’t listen for the response.cmd. And inside the “sendMessage”, I can’t get the response.cmd to trigger a function. Is there a solution for this, other than sending an all new message from the background script?
The code I am referring to:
Background.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if(request.cmd == "createSelectionMenu") {
sendResponse({cmd: "saveText"}); //Do things
}
});
Content_script.js
chrome.extension.sendMessage({ cmd: "createSelectionMenu", data: selectedText },
function(response) {
if(response.cmd == "saveText") {
createForm();
}
}
});
What I do is following:
I keep track of my opened tabs
content script:
// connect to the background script
var port = chrome.extension.connect();
background script
// a tab requests connection to the background script
chrome.extension.onConnect.addListener(function(port) {
var tabId = port.sender.tab.id;
console.log('Received request from content script', port);
// add tab when opened
if (channelTabs.indexOf(tabId) == -1) {
channelTabs.push(tabId);
}
// remove when closed/directed to another url
port.onDisconnect.addListener(function() {
channelTabs.splice(channelTabs.indexOf(tabId), 1);
});
});
Now I can notify all my registered tabs (i.e. content scripts) from my background script when a certain action happened:
var notification = { foo: 'bar' };
for(var i = 0, len = channelTabs.length; i < len; i++) {
chrome.tabs.sendMessage(channelTabs[i], notification, function(responseMessage) {
// message coming back from content script
console.log(responseMessage);
});
}
And again, on the other side in the content script, you can add a listener on these messages:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.foo == 'bar') {
executeStuff();
// if a callback is given:
sendResponse && sendResponse('success');
}
});
It's a bit of a brainf*ck, because it's redundant at some places. But I like it best that way, because you can wrap it and make it a bit easier.
If you want to see how I am using this, see my repository on GitHub: chrome-extension-communicator.

Message isn't passed between background.html and popup.html

I'm trying to pass data that is saved in sessionStorage from background.html to popup.html
background.html:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
data = sessionStorage.getItem(request.tabId);
alert(data);
sendResponse({ data: data });
});
and in popup.html:
chrome.tabs.getSelected(null, function(tab) {
chrome.extension.sendRequest({ tabId: tab.id }, function(response) {
alert(response.data);
});
});
The popup is opened by a pageAction button, when I click the button I get an alert box with "null" on the popup and then an alert box with the data that I stored in sessionStorage on the background!
Any ideas how to fix this?
You don't need to use message/request APIs. I think this response may help you.
You also don't need sessionStorage, just store your data in a global variable of the background page. It will persist until the browser is closed or until the extension is restarted.
So, here is how I would rewrite your code:
background.html:
var data = {}; // Object storing data indexed by tab id
and in popup.html:
chrome.tabs.getSelected(null, function(tab) {
alert(chrome.extension.getBackgroundPage().data[tab.id]);
});
Note that chrome.tabs.getSelected is deprecated since Chrome 16, so popup code should be:
chrome.windows.getCurrent(function(win) {
chrome.tabs.query({'windowId': win.id, 'active': true}, function(tabArray) {
alert(chrome.extension.getBackgroundPage().data[tabArray[0].id]);
});
});
Well, I've done something dumb.
I inspected the background page by opening chrome-extension://[extension-id]/background.html in a tab instead of clicking on "inspect active views: background.html" in the extensions management page. This caused the tab to catch the request and call sendResponse, but the popup expected the REAL background page to call sendResponse (and if I understand Google's documentation regarding message passing, the fact that sendResponse was called twice is root of the problem, because the first call clears the request object)

Resources