getting same origin policy error on getJSON in chrome extension - google-chrome-extension

My Chrome extension background.js checks if a condition is true, and if so, download a script from my server which makes changes to the DOM. Now I'm trying to make a jquery getJSON call from that downloaded script, again, to my server, but I'm getting a XMLHttpRequest cannot load https://www.mydomain.com/loadit.php?h=&fr=0&type=5&category=. Origin http://thisdomain.com is not allowed by Access-Control-Allow-Origin.]`
Now, my manifest file has the following:
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
Which I thought was supposed to allow cross origin requests from any url, so why am I getting the error?
EDIT: What's even stranger is that I'm inserting both an external css file and another js file (jquery) from that downloaded script, and both give me no problems. It's just that getJSON request that does...

ALthough I still don't know exactly why the extension wasn't allowing the cross-domain request, I was able to complete the request by using jquery.Ajax with Jsonp instead of the getJSON.

Related

how can i get the local file in chrome extension v3 [duplicate]

I have a Chrome extension that can (if you allow access to file URLs) grab your local pdf file that you have open in chrome and send it on to our API for processing. This is done by fetching the pdf with XMLHttpRequest to file:///Users/user/whatever/testfile.pdf from the background script.
When migrating to manifest v3 for a Chrome extension the background script becomes a service worker. In a service worker only fetch is available, not XMLHttpRequest. Problem is, fetch only supports http and https, not file:// urls. So how can I make the same feature of having the Chrome extension fetching/getting the local file?
EDIT: Things I also tried:
Making the XMLHttpRequest from injected iframe as suggested by answer.
This gives error net:ERR_UNKNOWN_URL_SCHEME when making the request
Making the XMLHttpRequest from injected content script.
This gives error Access to XMLHttpRequest at 'file:///.../testfile1.docx.pdf' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
From what I can understand from a lot of research access to file:// is in general blocked and Chrome extension background scripts used to be an exception to this. Seems to me it was never allowed from content scripts or action popups.
My manifest.json for reference:
{
"manifest_version": 3,
"name": "..",
"version": "0.1",
"icons": {
"16": "assets/icon-16x16.png",
"48": "assets/icon-48x48.png",
"128": "assets/icon-128x128.png"
},
"action": {
"default_title": ".."
},
"background": {
"service_worker": "background.js"
},
"permissions": [
"webRequest",
"activeTab",
"scripting",
"storage",
"unlimitedStorage",
"identity",
"pageCapture"
],
"host_permissions": [
"<all_urls>"
],
"web_accessible_resources": [{
"resources": ["iframe.html"],
"matches": [],
"extension_ids": []
}]
}
The content script is injected programmatically (using webextension-polyfill for promise support)
browser.action.onClicked.addListener(async (tab: Tab) => {
await browser.scripting.executeScript({files: [ "inject.js" ], target: {tabId: tab.id}});
});
Chrome 98 and older can't do it in the background service worker for the reasons you mentioned.
There was also a bug that prevented doing it in a normal visible chrome-extension:// page or iframe. It's fixed in Chrome 91.
Solution
Use fetch in Chrome 99 and newer.
In older versions use the following workarounds.
Workaround 1: File System API, Chrome 86+
A ManifestV3 extension can use the new File System API to read the contents of the file, for example inside the iframe exposed via web_accessible_resources.
Workaround 2. Extension frame, Chrome 91+
Use a content script that runs in the tab with that pdf:
matches in manifest.json should contain <all_urls> or file://*/* and file access should be enabled by the user in
chrome://extensions UI for your extension. Alternatively you can use
activeTab permission and programmatic injection when the user
clicks your extension's icon or invokes it through the context menu.
The content script adds an invisible iframe that points to iframe.html file exposed in web_accessible_resources
The iframe.html loads iframe.js which uses XMLHttpRequest as usual. Since the iframe has chrome-extension:// URL its environment
is the same as your old background script so you can do everything
you did before right there.
Workaround 3. Extension window/tab, Chrome 91+
An alternative solution is to use any other visible page of your
extension like the action popup or options page or any other
chrome-extension:// page belonging to your extension as they can
access the file:// URL via XMLHttpRequest same as before.
Notes
File access should be enabled in chrome://extensions page for this extension.

Is it possible to catch requests from another extension?

In my extension I use chrome.webRequest to catch requests from any web pages and it works like a charm.
But I can not catch any requests initialized from another extension.
My manifest:
"permissions": [
"tabs",
"webRequest",
"webRequestBlocking",
"<all_urls>"
],
background.js:
chrome.webRequest.onBeforeRequest.addListener(function (data) {
console.log('catched', data);
}, {urls: ['<all_urls>']});
Tests:
open tab with http://google.com:
catched https://www.google.com/
open extension console and run fetch('http://google.com'):
catched http://google.com/
open another extension console and run fetch('http://google.com'):
// no output
Does anybody know if is it possible and if so, how to set it up?
Thanks!
Updated
My previous answer it not correct, see #Rob W's comments.
But when #Xan mentioned that extension URLs were visible to other extensions, it became apparent that this behavior is undesirable and a security issue, so I removed the ability for extensions to see other extensions' requests
Previous answer
It's not allowed to handle requests sent from other extensions.
In addition, even certain requests with URLs using one of the above schemes are hidden, e.g., chrome-extension://other_extension_id where other_extension_id is not the ID of the extension to handle the request, https://www.google.com/chrome, and others (this list is not complete).

Fetch API not sending session cookies when used inside a Chrome Extension

I'm trying to make a Chrome Extension which scrapes some details from Pull Requests on Github using the Fetch API, and then displays them elsewhere. I'm running into some problems when I try to use this with a non-public repository on Github. I believe this is related to CSRF protection, and the rules that govern Chrome extensions having access to session cookies.
I have the following in my extension's manifest.json:
"content_scripts": [{
"matches": [
"*://github.com/*/*/pulls"
],
"js": ["script/underscore-1.8.3.min.js", "script/content.js"]
}],
"permissions": [
"tabs",
"activeTab",
"*://github.com/*",
"webNavigation"
]
But when I run the following from within my script/content.js:
fetch('/redacted/redacted/pull/4549', {credentials: 'same-origin'}).then((response) => {
return response.text();
}).then((text) => {
// do cool stuff
})
This produces a 404 response from Github. Inspecting this request with Chrome Inspector's network tab, I can see it is not sending my GitHub session header with the request.
If I make the very same request using the Javascript prompt in the Inspector, I can see a 200 response, and I can see that it is sending my session cookies.
My understanding was that specifying the Github domain in my manifest.json would mean my extension would have access to my session data in my content scripts, is this not correct? What should I be doing to make a valid request to this protected content?
According to Chrome blog, to include cookies you need credentials: 'include' instead of credentials: 'same-origin'.
Specifying github in the permissions only gives access to the host, its there to limit damage if the extension/app is compromised by malware (source).
Its not indicated in the content script documentation that session data can be retrieved in content scripts, just their DOMs. I think it would be better if you use and incorporate the official Github API in the chrome extension project you're creating.

chrome extension can get data from http://www.foo.com/api but not http://www.foo.com/api/data.xml

I'm writing an extension that requests XML content from a server and displays data in a popup/dialog window. I've added the website to my manifest.json permissions like so:
"permissions": [
"http://*/*"
],
Later I added the following code to my background page:
function loadData() {
var url = "http://www.foo.com/api/data.xml";
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
...
xhr.send();
the problem is, that I get the cross-site security error "Origin chrome-extension://kafkefhcbdbpdlajophblggbkjloppll is not allowed by Access-Control-Allow-Origin. "
The thing is, with "http:///" in the permissions I can request "http://www.foo.com/api", but I can't find any way to allow "http://www.foo.com/api/data.xml".
I've tried both "http:////*" and http://www.foo.com/api/data.xml" in the "permissions". What else should I be doing?
This should work (SOP doesn't apply to chrome extensions),so there are three possibilities:
There is some mistake somewhere
Just to make sure use add <all urls> permission and check that extension really have this permission. (e.g. execute chrome.runtime.getManifest() in console when inspecting background page )
Server itself is checking Origin header and is rejecting request if origin value is unexpected
You can quickly check this by using some http tester and sending request manually (for example Dev Http Client for chrome, since I'm one of the developers). If it shows the same error, it means that the server is really checking origin header.
To fix this you will have to make server somehow accept your origin , or you can use chrome.webRequest to set valid origin header to all the requests sent to the target server (standard XHR api doesn't allow modification of Origin header)
Chrome bug
Well in this case you can only report this error and wait for the best

How do I call SignalR in a chrome extension background page for specific host?

I'm trying to use SignalR in a chrome extension on a background page.
Everything seems to work fine until it tries to call negotiate. It seems to be taking the caller (which is a chrome-extension background page) and trying to call negotiate against that, which gives me a 404 while trying to call this page:
chrome-extension://edcdcfjmmmchhgmomfemdkomibeoloko/signalr/negotiate?_=1372007788595
I'd imagine that it should be calling
https://myserver.com/signalr/negotiate?_=1372007788595
But I don't know how to override SignalR with a specific host. Can I override SignalR to work in a chrome extension on a background page
I assume it is javascript you are using? Try
$.connection.hub.url = "http://myserver.com/signalr";
This took me a couple hours to figure out but here's a few steps to get going on making signalr work with a google chrome extension.
Place within the javascript
$.connection.hub.url = "http://yoursever.com/signalr"`
Within the manifest.json file for the google chrome you must give permission to access the server. I would add something like this to make it easy.
"permissions": [
"http://*/*",
"https://*/*"
]
Within your global configuration you need to change allow cross domain requests. Change
RouteTable.Routes.MapHubs()
to
RouteTable.Routes.MapHubs(new HubConfiguration()
{
EnableCrossDomain = true
});

Resources