Chrome extension - Get http status code from tab update - google-chrome-extension

I'm trying to load a page in a tab and get the status code returned.
I'm updating the tab using
chrome.tabs.update({
url: url
})
I have the following listener set up, but for some reason it's never being called.
chrome.webRequest.onCompleted.addListener(function processLoadPage(details) {
console.log(`Got http status code ${details.statusCode}`);
}, { urls: ["<all_urls>"] });
I tried using chrome.tabs.onUpdated.addListener which does get called and has a status but I don't see anyway to get the actual http status code from this.
I'm using manifest v3 and this is running in a service worker. I have the following permissions
"permissions": [
"storage",
"downloads",
"tabs",
"activeTab",
"scripting",
"webRequest",
"webRequestBlocking",
"<all_urls>"
],

Related

Chrome Extension Manifest matches not working for clicking into that url

I have the following manifest
{
"manifest_version":2,
"name": "HelloWorld",
"version": "0.1",
"content_scripts": [
{
"matches": [
"*://www.mywebsite.com/"
],
"js": ["home.js"],
"run_at": "document_start"
}
]
}
It works perfectly when I enter www.mywebsite.com through browser url bar. But when I route to the same url www.mywebsite.com through hyperlinks in another url, the script does not trigger. Why is that? I do not see this in
I just figured out a temporary method, you can do
<some_dom_object>.addEventListener("click", function() {
// do the thing you want happen.
})
on that "button element" or "anchor element" or whatever that you clicked to that website, so the code will get executed also when you "click" to the url.

content_script not running on GitHub when following links

I am writing a Chrome Extension mainly for Pull Requests on Github Enterprise and have ran into an issue. When the page is loaded via a refresh or direct entering of the url from your browser it runs, when it is ran from clicking a link within Github it does not.
For instance if you go to this page with Pull Requests and click into one of them it will not run. But if you refresh that same page it will run.
manifest.json
{
"name": "Github Sample",
"manifest_version": 2,
"version": "0.0.1",
"description": "Sample",
"permissions": [
"tabs", "<all_urls>",
"http://github.com/*"
],
"content_scripts": [
{
"matches": [ "https://github.com/*" ],
"js": ["github.sample.js"],
"run_at": "document_end"
}
]
}
github.sample.json
// ==UserScript==
// #author Jacob Schoen
// ==/UserScript==
alert("Extension has Ran");
To make this easier I have pushed this to github.
Any ideas on how to address this?
GitHub site uses jquery-pjax library (see How to make github style page transitions by pjax).
Basically you only need to run the content script once and attach pjax event handlers inside an injected <script> element code which will be reusing a jQueryor $ variable of the site.
In those handlers you can send a message with document.dispatchEvent to your content script that will receive it in its window.addEventListener("blabla", ...)
or you can allow the access to chrome.runtime.sendMessage on the github site in manifest.json so that page-injected code will be able to send a message that can be received by the extension in chrome.runtime.onMessageExternal listener.
Alternatively you can use chrome.webNavigation.onHistoryStateUpdated in the background script but that will cause a warning during the installation that the extension can "Read your browsing history" which is a global permission unlike the content script solution.
The working example I came up with, in case it helps anyone else.
manifest.json
{
"name": "Github Sample",
"manifest_version": 2,
"version": "0.0.1",
"description": "Sample",
"permissions": [
"activeTab",
"tabs", "<all_urls>",
"http://github.com/*"
],
"content_scripts": [
{
"matches": [ "https://github.com/*" ],
"js": ["github.sample.js"],
"run_at": "document_idle"
}
],
"web_accessible_resources": ["inject.js"]
}
github.sample.js
// ==UserScript==
// #author Jacob Schoen
// ==/UserScript==
function myAlert() {
alert("Extension has Ran");
}
window.addEventListener("pageLoadTransition", myAlert);
var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.extension.getURL('inject.js');
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
//still have to load this one for direct page loads
myAlert();
inject.js
$(document).on('pjax:success', function() {
var evt=document.createEvent("CustomEvent");
evt.initCustomEvent("pageLoadTransition", true, true, null);
document.dispatchEvent(evt);
})
I also updated the Github repository with the working example.

Chrome API (chrome.topSites.get) is not ready during browser start

Did anyone get a situation when chrome API didn't available during browser start
I have catch the situation when I didn't get "callback happen" in log only during browser start on one test computer
chrome.topSites.get(function(data) {
console.log("callback happen");
});
add topSites in permission tab
manifest.json
"permissions": [
"tabs",
"activeTab",
"topSites", << Add this
"http://*/*",
"https://*/*"
],
"browser_action": {
"default_popup": "popup.html"
}
and in popup.html add js file and write
chrome.topSites.get(function(t) { console.log('Here I am inside topSites')});
it's working on my side.

"Not allowed to load local resource: chrome://favicon/"

Im trying to load a url's favicon using chromes favicon url:
<img class='icon' src='chrome://favicon/yahoo.com' />
But im getting the error :
"Not allowed to load local resource: chrome://favicon/yahoo.com"
And in the manifest i have:
"permissions": [
"chrome://favicon/"
],
There isnt much available online about this topic. Any suggestions?
Problems in your code
"permissions": ["chrome://favicon/"], is an invalid pattern in manifest file
If you want to use the URL of the tab's favicon use chrome.tabs API in extension pages.
Demonstration
manifest.json
Registered background page and added necessary permissions.
{
"name": "Fav Icon",
"description": "http://stackoverflow.com/questions/14800881/not-allowed-to-load-local-resource-chrome-favicon",
"version": "1",
"manifest_version": 2,
"background": {
"scripts": [
"background.js"
]
},
"permissions": [
"tabs",
"<all_urls>"
]
}
background.js
chrome.tabs.query({
"active": true,//fetch active tabs
"currentWindow": true,//fetch tabs in current window
"status": "complete",//fetch completely loaded windows
"windowType": "normal"//fetch normal windows
}, function (tabs) {
for (tab in tabs) {
console.log(tabs[tab].favIconUrl);// Use this URL as needed
}
});
chrome.tabs.query will work in extension pages, if you want to use in content scripts use message passing to communicate URL.
References
chrome.tabs API
Message Passing
The URL needs to include the scheme as well:
<img src="chrome://favicon/http://www.yahoo.com">
Just ran into this issue and both
"permissions": ["chrome://favicon/"] and "permissions": ["chrome://favicon/*"]
worked as expected.
Chrome version 52.0.2743.116
Well, I know it's an old post but for those who are here to find this answer, why it is showing like this is basically because chrome://favicon/ and chrome://favicon/* both should be added in your mainfest.json
"permissions": ["chrome://favicon/", "chrome://favicon/*"]
NOTICE: mainfest v3 will have API dedicated to this but for now we don't have much blogs on that and also mainfest v2 will be no longer supported after 2023.
You can now use favicon as the permission with _favicon/?pageUrl=${url}&size=32 to load icons
Here is an example
Unfurtunely it will not work as it was in manifest v2. You have to use it differently.
Method 1 (lazy)
https://www.google.com/s2/favicons?domain=https://stackoverflow.com/
Method 2 (official)
manifest.json
"permissions": [
"favicon"
],
export const favicon = (pageUrl: string, size: number = 24) => {
const url = new URL(`chrome-extension://${chrome.runtime.id}/_favicon/`);
url.searchParams.append("pageUrl", pageUrl);
url.searchParams.append("size", size.toString());
return url.href;
};
favicon("https://stackoverflow.com/");
Additionaly add loading="lazy" attribute for you image, to prevent hundreds request.

Chrome extension background.html not logging to console

I'm having trouble getting my content script to communicate with my background page. I'm running an unpacked extension. In my content script send.js I have a line
chrome.extension.sendRequest({message: "hey"}, function(response){});
and my background.html looks like:
<script>
/* the coffeescript way, but I also tried without the
* coffeescript wrappers and got the same errors. */
(function() {
var dispatchRequest;
dispatchRequest = function(request, sender, sendResponse) {
console.log("request dispatch called");
}
chrome.extension.onRequest.addListener(dispatchRequest);
}).call(this);
</script>
I keep getting a Port error: Could not establish connection error.
Just to try to find the error I changed my background.html to
<script>
console.log("Background html is running!");
</script>
I then reloaded the page and checked the Chrome console but there was no output.
Here's my (abbreviated) manifest.json:
{
"background-page": "background.html",
"content_scripts": [{
"all_frames": true ,
"css": [ "style.css" ] ,
"js": [ "send.js" ] ,
"matches": [ "http://mail.google.com/*" ,
"https://mail.google.com/*" ]
}],
"permissions": [ "tabs", "http://*/", "https://*/", "cookies" ]
}
At this point I'm at a loss to figure out how to get the background.html to run or how to get my content script to communicate with it.
Assuming it's not just a transcription error, the manifest key for the background page should be background_page, not background-page.

Resources