How to call a Javascript function declared in my extension, using a html button from my web page?
I have a html page, with a button inside. When the user click the button, it will call a function that I already declared inside my own firefox extension.
Since you control the web page, the easiest and the safest method to do what you want would be to dispatch a custom DOM event in the web page and listen to it in the extension code:
https://developer.mozilla.org/En/Code_snippets/Interaction_between_privileged_and_non-privileged_pages
Here's an example extension I wrote that does exactly this http://mozilla.doslash.org/cw/ (not updated to the most recent Firefox version, but it's clean and should be easy to update).
Your Firefox extension runs in a different Javascript context to your HTML page, so the extension cannot be directly called from the Javascript in your HTML page.
However, you can design the extension to allow access from HTML. HTML Javascript isn't generally allowed to access the Component object, so you need to allow the HTML code a way to get at the object in your extension. To do this, create an XPCOM component in your extension, and set the object in the "JavaScript global property" category through the nsICategoryManager object. The entry name is the string used from unprivileged Javascript, the value is the contract ID for your XPCOM class.
However, you also need to allow unprivileged Javascript access to your object, or the script security manager will block access. To allow this, implement nsISecurityCheckedComponent - providing canCreateWrapper(in nsIIDPtr iid), canCallMethod(in nsIIDPtr iid, in wstring methodName), canGetProperty(in nsIIDPtr iid, in wstring propertyName) and canSetProperty(in nsIIDPtr iid, in wstring propertyName) to return allAccess for the allowed properties, and noAccess otherwise.
Be careful what you do with user input, and what you allow access to - it is very easy to accidentally create a security hole in the browser doing this.
Try to put this at the beginning of your javascript function that tries to access a local file:
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
This will give the user the choice as to whether they want to allow your code to access the local filesystem.
Related
I am working on a web app that needs to have two parts. The one is a controller and the other is a display. Something like Google Slides in presentation mode. The controller has a button to launch the display:
<script language="JavaScript">
function OpenMain()
{
var MainPage = window.open("TheUltraSignalLite.html");
TimerIMG = MainPage.document.getElementById("TimerIMG");
TimerIMG.src = "TM-Full-Blue.jpg";
}
</Script>
The call to window.open seems to return null. I have tried Chrome, Edge, Firefox, and Opera and they all have the result. These are all local files for now, but I might put in on a web server someday. I have seen some answers that want you to turn off security, but I cannot ask everyone who uses this app to turn off security. How do I get a valid reference to the display window?
Edit 1:
Yes, window.open from the local disk does cause a CORS restriction.
I tried this where both files are in the same AWS S3 Bucket, so the CORS should not be an issue. But I still get a null on the window.open. If I put a breakpoint on the first line, then everything worked. If I split the open and the rest of the code into two functions with two buttons, it works. So it looks like I have to find a way to run the open in an async way.
Edit 2
My solution to keep it simple was to put the window.open in the OnLoad event. This opens the child window and allows it to fully render and the value of MainPage is ready to use. (I changed the MainPage to a global variable.) I still have to run it from some type of web server, rather than loacl file, but that is not a big deal.
If you are not allowed to access the new window content, then the problem you are encountering is a basic security feature of web browsers. Citing mdn:
The returned reference can be used to access properties and methods of the new window as long as it complies with Same-origin policy security requirements
To read more about Same-origin policy
If your new window respects the Same-origin policy, then you can access the content of the new window with for example:
// Open index.html from the current origin
const newWindow = window.open('index.html')
const h1 = newWindow.document.querySelector('h1')
If you want to avoid asking users for pop-up permission, then you should probably use a link instead of a pop-up.
In the following code
browser.runtime.getBackgroundPage().then(bgp=>{
document.querySelector("button").addEventListener("click", e=>{
alert(bgp);
});
});
bgp turns out to be null. I searched around and suggestions are most of the time for Chrome extensions, suggesting adding a "background" permission, which is not valid for Firefox. I also tried adding a background page explicitly, although one should be always created for me but it did not work either.
runtime.getBackgroundPage() provides access to the background script, not an HTML document.
This provides a convenient way for other privileged extension scripts
to get direct access to the background script's scope. This enables
them to access variables or call functions defined in that scope.
"Privileged script" here includes scripts running in options pages, or
scripts running in browser action or page action popups, but does not
include content scripts.
For example, the following code logs <unavailable> to the console.
browser.runtime.getBackgroundPage().then(bg => console.log(bg));
The window object can be seen in the debug console.
I have set up an Articulate Storyline course (a Flash version accessed using the page "story.html" and an HTML5 version accessed using "story_html5.html"). It works fine when run directly, however, when I try to run everything in an iframe on the company server (linking to the course files on my personal server) I get JavaScript errors:
The course uses player.GetVar("HTML5spelaren") to access a variable called HTML5spelaren, which is located on the story_html5.html page itself. When running in an iframe I get a "Permission denied to access property 'HTML5spelaren'".
Finally the course uses the JavaScript var newWin=document.window.open("report.html", "Kursintyg"); to display a course completion certificate in a new window. When running in an iframe however this results in a "Permission denied to access property 'open'".
Is there a way to rewrite the JavaScripts to get around this? I need to be able to detect if the course is running in Flash or HTML5 mode (that's what I use the variable in story_html5.html for), as well as being able to use JavaScript to open a new page from within the iframe when clicking on a link.
Page structure:
https://dl.dropboxusercontent.com/u/11131031/pagestructure.png
/Andreas
There's a way for different domains to speak to one another via javascript. You can use postMessage: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
In your case, in story.html or story_html5.html could use something like:
parent.postMessage(HTML5spelaren, parent_domain);
and you add an event listener in the company page:
window.addEventListener("message", receiveMessage, false);
And in receiveMessage function you retrieve the data that you need. Something like:
function receiveMessage(event){
your_variable = event.data
}
Same logic can be probably be applied to your popup.
You can post from child to parent or from parent to child.
My guess is that content you're linking to in the iFrame is on a different server/domain. If so, the error is a security feature to stop cross-site scripting (XSS) attacks.
Consider putting both the parent iFrame and the articulate content (child) on the same server. This should eliminate the problem.
I'm building a Chrome extension and using the db.js wrapper to utilize the indexeddb. The problem is, I've got several subdomains and I'd like to be able to share the information across them.
When I use the Chrome Dev tools to view Resources, all of the individual subdomains have their own copy of the schema I'm creating, and each has it's own data.
The only thing I knew to try was to set the document.domain but that didn't help. I wasn't surprised.
Documentation on indexeddb is very slim it seems. I keep finding the same 2 or 3 blog posts copied word for word in several different blogs and nothing specifies that this is possible or impossible.
You can't access the same database from multiple subdomains, the access scope is limited to html origin.
html_Origin = protocol + "://" + hostname + ":" + port + "/";
As #Xan mentioned, if you can use a common origin owned by the extension itself, rather than by the content pages, that sounds like it would be by far the easiest solution. If for whatever reason you can't do that (or for readers who got here wanting to know about regular page javascript or Greasemonkey-style userscripts, rather than extensions), the answer is:
Yes, though it's a slightly awkward and takes some work:
Since you're using a number of related subdomains, (rather than completely unrelated domains), there's a technique you can use in that situation. It can be applied to IndexedDB, localStorage, SharedWorker, BroadcastChannel, etc, all of which offer shared functionality between same-origin pages, but for some reason don't respect modifications to document.domain.
(1) Pick one "main" subdomain to for the data to belong to. i.e. if your subdomains are https://a.example.com, https://b.example.com, and https://c.example.com, you might choose to have your IndexedDB database stored under the https://a.example.com subdomain.
(2) Use it normally from all the the https://a.example.com pages.
(3) On https://b.example.com and https://c.example.com, use javascript to set document.domain = "example.com";. Then also create a hidden <iframe>, and navigate it to some page on the https://a.example.com domain (It doesn't matter what page, as long as you can insert a very little snippet of javascript on there. If you're creating the site, just make an empty page specifically for this purpose. If you're writing an extension or a userscript and so don't have any control over pages on the example.com server, just pick the most lightweight page you can find and insert your script into it. Some kind of "not found" page would probably be fine).
(4) The script on the hidden iframe page need only (a) set document.domain = "example.com";, and (b) notify the parent window when this is done. After that, the parent window can access the iframe window and all its objects without restriction! So the minimal iframe page is something like:
<!doctype html>
<html>
<head>
<script>
document.domain = "example.com";
window.parent.iframeReady(); // function defined & called on parent window
</script>
</head>
<body></body>
</html>
If writing a userscript, you might not want to add externally-accessible functions such as iframeReady() to your unsafeWindow, so instead a better way to notify the main window userscript might be to use a custom event:
window.parent.dispatchEvent(new CustomEvent("iframeReady"));
Which you'd detect by adding a listener for the custom "iframeReady" event to your main page's window.
(5) Once the hidden iframe has informed its parent window that it's ready, script in the parent window can just use iframe.contentWindow.indexedDB, iframe.contentWindow.localStorage, iframe.contentWindow.BroadcastChannel, iframe.contentWindow.SharedWorker instead of window.indexedDB, window.localStorage etc. ...and all these objects will be scoped to the https://a.example.com origin - so they'll have the this same shared origin for all of your pages!
The "awkward" part of this technique is mostly that you have to wait for the iframe to load before proceeding. So you can't just blithely initialize IndexedDB in your DOMContentLoaded handler, for example. Also you might want to add some error handling to detect if the hidden iframe fails to load correctly.
Obviously, you should also make sure the hidden iframe is not removed or navigated during the lifetime of your page... OTOH I don't know what the result of that would be, but very likely bad things would happen.
And, a caveat: setting/changing document.domain can be blocked using the Feature-Policy header, in which case this technique will not be usable as described.
However, there is a significantly more-complicated generalization of this technique, that can't be blocked by Feature-Policy, and that also allows entirely unrelated domains to share data, communications, and shared workers (i.e. not just subdomains off a common superdomain). #Xan alludes to it in point (2) of his answer:
The general idea is that, just as above, you create a hidden iframe to provide the correct origin for access; but instead of then just grabbing the iframe window's properties directly, you use script inside the iframe to do all of the work, and you communicate between the iframe and your main window only using postMessage() and addEventListener("message",...).
This works because postMessage() can be used even between different-origin windows. But it's also significantly more complicated because you have to pass everything through some kind of messaging infrastructure that you create between the iframe and the main window, rather than (for example) just using the IndexedDB API directly in your main window's code.
HTML-based storage (indexedDB, localStorage) in Chrome extensions behaves in a way that might not be expected, but it's perfectly natural.
In the background page, the domain is chrome-extension://yourextensionid/, and this is shared by all extension pages and is persistent.
In the content scripts though, you're sharing the HTML storage with the domain you're operating on. This makes life difficult if you want it to share/persist things. Note that sometimes this behavior is actually helpful.
The universal solution is to keep the DB in a background script, and communicate data/requests by means of Messaging API.
This was the usual solution for localStorage use until chrome.storage came along. But since you're using a database, you don't have a ready extension-friendly replacement.
my firefox extension has an object myExt .
myExt = {
request: function(){
//adds dynamic script element to the current webpage's head tag
},
callback: function(json) {
//do something with this
}
};
myExt.request adds a dynamically added script element to a server that returns json, i want the json to be sent to myExt.callback that exists within my extension's js code.
from my extension
//from my extension, i add a script element
myExt.request();
pings the server, back into the webpage
//from server i get the following response
myExt.callback ( {"some":"json"}) ;
//but the window doesnt find a reference to myExt
how do i make a reference to myExt variable from the webpage ?
Firefox extensions run JavaScript with high privilege (chrome) and have full access to the browser. JavaScript code from a web page run unprivileged JavaScript and among other things cannot reference or interact directly with the privileged JavaScript.
In general, you have to be very careful when your extension code interacts with code coming from websites in order not to open a security hole that could allow a malicious website to execute JavaScript with chrome privileges.
You can find more information here, including code snippets if you need to exchange data between privileged and unprivileged JavaScript:
https://developer.mozilla.org/en/Security_best_practices_in_extensions
See also this link to exchange data between privileged and unprivileged JavaScript:
https://developer.mozilla.org/en/Code_snippets/Interaction_between_privileged_and_non-privileged_pages