Porting a chrome extension to firefox - javascript

First of all: This is no duplicate of "how to automaticly convert a chrome extension"...
I wrote a complex chrome extension which is quite popular. So a lot of people asked me to publish a firefox - version.
I am currently in a quite early state of analyzing the difficulties I might run into. I am able to map most chrome-specific commands to others in firefox.
Just one topic is unsolved until now:
Chrome uses content-scripts and background-scripts.
the communication works that way:
Content-Script:
chrome.runtime.sendMessage(
{
Action: "LoadAll"
}, function(response)
{
mySetting= response.Setting;
}
);
background-script:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse)
{
if (request.Action === "LoadAll")
{
sendResponse({Setting: "hello out there!"});
return true;
}
)
});
(please ignore if I might have missed a bracket)
How is this communication been done on firefox extensions? Or does FF recommend a complete different approach?
If there is no "Take this command" - answer, a link to a more in-depth-explanation would be nice.

The thing you are looking for is Message Manager. We are developing a big and complicated extension for about 2 years for Fx and recently made a good Chrome port of it. Messaging process differs strongly in Fx and Chrome. Think of it like you inject a content script in window/browser/tab, which has few things in common with content scripts in Chrome, and then talk to your extension code from injected script via sendSyncMessage/sendAsyncMessage. I hope this helps.

Related

Is it possible to alter the Google Chrome Offline page with a Chrome extension? [duplicate]

This question already has answers here:
How to execute a custom script on the Chrome's Dino offline game on current tab?
(1 answer)
Can you access chrome:// pages from an extension?
(3 answers)
Closed 12 months ago.
I am working on a Chrome extension for my company.
For fun, and just because I like easter eggs and I like to work an extra mile to always give a good experience for my users, I thought about replacing the Running Dinosaur game on the offline page by something branded for our company as a fun surprise. I like to develop 2D games sometimes, and I'd have fun doing this.
I migrated the Chrome extension to the manifest v3 recently (I will write a medium article on this as it was quite challenging and I had to find so many hacks to keep our extension working).
I was thinking about using the chrome.scripting.executeScript API.
What I tried so far is to add a listener on a new tab opening
using this API chrome.tabs.onUpdated.addListener and look for the status: 'complete'. Then use the executeScript this way:
chrome.tabs.onUpdated.addListener((tabId, changes, tab) => {
if (tab.status === 'complete') {
if (!navigator.onLine) {
chrome.scripting.executeScript({
target: {
tabId,
},
files: [
'/static/js/easter.js',
],
});
}
}
});
In my script for now I just console.log('loaded') to check if my script is properly injected. When I am online, the script loads successfully on the tabs, but when I switch to offline mode (using the developer network tab or actually disconnecting the wifi), the script fails to load and I get this error in the tab's console even though, the host_permissions seems to be configured properly in the manifest.json file:
Unchecked runtime.lastError: Cannot access contents of the page. Extension manifest must request permission to access the respective host.
I am not sure why it throws this error and I was wondering if anybody had the same issue and if you managed to solve this.
Thank you for your help!

How get raw response body inside a Web Extension for Firefox 55?

I try to get the raw response body inside a Web Extension using Firefox 55.0.3.
Only "solutions" I have seen for now:
Repeat the request (I absolutly don't want to repeat the request)
Using Javascript to get innerHTML attribute of HTML tags such as head and body (tell me if I'm wrong, but with a solution like that I will not always have the whole content, for example I will get nothing in case of response without HTML. So it will never be the real raw response and in some case it will simply not work.)
Also, I saw this answer for Chrome (from 2015) using the debugger, but I wasn't able to do it with Firefox. This kind of solutions are interesting, I read Mozilla documentation about devtools but I didn't find a way of using the network tab of webtools interface with Javascript inside a Web Extension.
To give you more details, my goal is to intercept the full request and response from server (header and body). This is not a problem to do it, except for the response body.
Here an example of code to get the request body: (background script)
browser.webRequest.onBeforeRequest.addListener(
function (e) {
console.log(e);
},
{urls: ["http://*/*", "https://*/*"]},
["requestBody"]
)
Here some documentations that I used (there is more, but these links are all official):
Mozilla documentation about Web Extension
Intercept HTTP requests
webRequest
webRequest.onHeadersReceived
webRequest.onBeforeRequest
webRequest.onBeforeSendHeaders
Here some examples of Web Extensions.
Any ideas, solutions or even explainations "why this is not possible" are welcome, thank you in advance for your time !
Cheers++
This is now available, as of Firefox 57:
browser.webRequest.filterResponseData allows you to add a listener via browser.webRequest.onBeforeRequest which receives, and allows you to modify the response.
You can see an example in the Mozilla github webextensions-examples repo
Firefox 57 is going to provide the API browser.webRequest.filterResponseData. This doesn't seem to be documented yet, but you can look through bug 1255894 for details.
Why is this not possible?
For the simple reason that WebRequest was ported over from Chrome extensions, where this is explicitly impossible.
Requests for such functionality (to edit, or just to read) has been around for a very long time (since 2011 and 2015 respectively); they are challenging from both the security perspective and technical perspective, however a principal agreement that read access is a good idea is there.
However, it's simply not yet implemented. Rob W has been doing some work in this direction but it's not done yet.
Perhaps Firefox has a different implementation?
A cursory glance on Mozilla bugtracker doesn't find any bugs on providing this functionality. So, it's not likely that the implementation will diverge anytime soon.
Any workarounds?
Well, only the debugger-level access can touch actual response data.
Since debugger is not implemented in the WebExtension platform, only a devtools.network-using extension can access it - and only while Dev Tools are open for the tab making said request, which is the main limitation of devtools.* APIs.

Service Worker Install fails: "cannot read property 'addAll of undefined"

So I'll keep this succinct: When trying to install, my service worker fails. This is all of my code in sw.js:
var cacheName = 'randomstring';
var filesToCache = [ '/' ];
self.addEventListener('install', function (e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName)
.then(function (cache) {
console.log('[ServiceWorker] About to fail');
return cache.addAll(filesToCache);
})
);
});
I get an exception because cache is undefined (on the cache.addAll bit).
Not really sure why this is the case?
I've used service workers before and never encountered this issue. This is my first time using a service worker with an ASP.Net back-end though, so not sure if that's the problem?
So, I figured this out. I was going to vote to close the question, but I figured I'd leave it here as I saw some other people with this issue who didn't know how to resolve it. Even though it's super-stupid :) (or more accurately, I am).
So I was running the website via the "Play" button, aka "Start Debugging", which, in Visual Studio 2017, launches a special Chrome window, in which the above error will be thrown.
To work around the issue, I can (or you can, internet traveller of the future) simply start without debugging, host the website in IIS, etc.
EDIT: If there's a better workaround where I can use the service worker in debug mode, please suggest it and I'll mark that as the answer. For my specific problem though, the above workaround is fine :).
Encountered the same problem and found some other ways.
VS recognises "chrome.exe" while debugging and adds some parameters, that´s why service workers won´t working.
There is an option Debug => Option => Debugging => General => Enable javascript debugging for asp.net (Chrome, Edge and FireFox). If you don´t want to use js debugging in vs - like me because i use chrome for js debugging - just deactivate this option and service workers will work.
VS Enable JS Debugging in Chrome
Alternatively you can add chrome as a new "browser" and switch the browser for debugging. Because vs recognise "chrome.exe" make a symlink via administative commandline "mklink chromedirect.exe chrome.exe" and add it as new browser in visual studio.
This can be done under the "Play" context menu => Browse with.
VS Play Context Menu
Just add chromedirect.exe without any arguments and a friendly name like "Google Chrome Direct". After that you can switch to the browsers and select if you want VS JS Debugging or not.

Chrome extensions communication (content scripts)

I got 2 extensions in Chrome, both only uses content scripts at the moment. Both extensions listen on websocket for messages from the server. Also they both get the same message "same" (obviously a minimal difference) time. After they got the message they both process it and at the end they both have a result which is an int number.
What I would like to do is sending this number from extension A to extension B and from ext. A to ext. B so they both have the other's result.
I've really tried to google a solution for this, but I couldn't find any. Also I would like to avoid sending the results back to the server and then back to the extensions again.
Is there any way (preferably only JS) to do this?
Thanks!
This has been discussed here: Can Chrome extensions communicate with each other?
you can use this api: https://developer.chrome.com/extensions/messaging#external
chrome.runtime.sendMessage(otherExtensionId, {msg: 'hello'},
function(response) {
if (response.msg='hi')
chrome.runtime.sendMessage(otherExtensionId, {msg: 'how are you?'});
});
and in the other extension:
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (request.msg=='hello') {
sendResponse({msg: 'hi'});
}else ifif (request.msg=='how are you?'){
doSomething()
}
});
also for another means of communication, you can create an invisible div inside your page, and have both extensions constantly checking if it's contents change.

Windows Phone 8 IE10 Javascript debugging

IE10 has some wonderful enhancements in the HTML5 compliance area but remains a bear to develop JavaScript HTML5 when running on the WP8 as there is no way to debug the app except console messages.
Is there a remote debugging experience available for IE10 running on WP8 like the WebKit phone browsers have(see my video at http://www.youtube.com/watch?v=GNAjzFpNEj4 for example). When this is in place with a USB cable to desktop Safari debugging Javascript apps on IOS is easy as breakpoints can be set and variables examined in the remote debugger . I am hoping the same capabilities are in IE10 and would appreciate any information on where to enable these very much needed capabilities.
The bad news, that there is no new debug capabilities in comparison to WP7/IE9. Please take a look on How do I debug Internet Explorer on Windows Phone 7? since we are in exactly the same situation on WP8.
What I personally use on daily basis
Debug your app in IE10 Desktop as much as possible
Weinre remote debugger. Demo video. You can use the following app based on Weinre to simplify its usage (no local setup needed) - IeMobileDebugger src or link to Store
Supports
Html traversing
Html node styles, properties, metrics
Reading console output
Executing js on device side from console (including intellisense)
Dynamic script injection - ability to debug live sites
Not supported
js breakpoints
For javascript line by line debugging use aardwolf. Demo with VS integration.
To redirect console trace to Visual Studio output and be able to use console.log("some message") for tracing
index.html:
<script type="text/javascript">
window.console = {
log: function (str) { window.external.Notify(str); }
};
// output errors to console log
window.onerror = function (e) {
console.log("window.onerror ::" + JSON.stringify(e));
};
console.log("Installed console !");
</script>
MainPage.xaml.cs
private void Browser_Loaded(object sender, RoutedEventArgs e)
{
Browser.IsScriptEnabled = true;
// Add your URL here
Browser.Navigate(new Uri(MainUri, UriKind.Relative));
Browser.ScriptNotify += (s, arg) =>
{
Debug.WriteLine(arg.Value);
};
}
FWIW: Windows Phone 8.1 finally supports remote debugging. See http://blogs.msdn.com/b/visualstudioalm/archive/2014/04/04/diagnosing-mobile-website-issues-on-windows-phone-8-1-with-visual-studio.aspx
While not a full solution, Lauri Piispanen's consolelog.js, a nodejs-based remote JS console logger could help you.

Categories