In Chrome extensions, why use a background page with HTML? - google-chrome-extension

I understand that the background page of a Chrome extension is never displayed. It makes sense to me that a background page should contain only scripts. In what situations would HTML markup ever be needed?
At https://developer.chrome.com/extensions/background_pages there is an example with an HTML background page, but I haven't been able to get it to work (perhaps because I am not sure what it should be doing).
Are there any examples of simple Chrome extensions which demonstrate how HTML markup can be useful in a background page?

Historical reasons
The background page is, technically, a whole separate document - except it's not rendered in an actual tab.
For simplicity's sake, perhaps, extensions started with requiring a full HTML page for the background page through the background_page manifest property. That was the only form.
But, as evidenced by your question, most of the time it's not clear what the page can actually be used for except for holding scripts. That made the entire thing being just a piece of boilerplate.
That's why when Chrome introduced "manifest_version": 2 in 2012 as a big facelift to extensions, they added an alternative format, background.scripts array. This will offload the boilerplate to Chrome, which will then create a background page document for you, succinctly called _generated_background_page.html.
Today, this is a preferred method, though background.page is still available.
Practical reasons
With all the above said, you still sometimes want to have actual elements in your background page's document.
<script> for dynamically adding scripts to the background page (as long as they conform to extension CSP).
Among other things, since you can't include external scripts through background.scripts array, you need to create a <script> element for those you whitelist for the purpose.
<canvas> for preparing image data for use elsewhere, for example in Browser Action icons.
<audio> for producing sounds.
<textarea> for (old-school) working with clipboard (don't actually do this).
<iframe> for embedding an external page into the background page, which can sometimes help extracting dynamic data.
..possibly more.
It's debatable which boilerplate is "better": creating the elements in advance as a document, or using document.createElement and its friends as needed.
In any case, a background page is always a page, whether provided by you or autogenerated by Chrome. You can use all the DOM functions you want.

My two cents:
Take Google Mail Checker as an example, it declares a canvas in background.html
<canvas id="canvas" width="19" height="19">
Then it could manipulate the canvas in background.js and call chrome.browserAction.setIcon({imageData: canvasContext.getImageData(...)}) to change the browser action icon.
I know we could dynamically create canvas via background.js, however when doing something involving DOM element, using html directly seems easier.

Related

Using jquery for parsing causes image network traffic in Chrome extension?

I'm writing an extension that scrapes web pages using jquery. After a while I start getting net errors saying resources not available and errors in the console loading images in the pages I'm scraping. I thought it might be $.get() loading it as html somehow, but it still happens when I use a raw XMLHttpRequest and it appears even when I call $(text) with static text.
Looking in the application tab of my background page I can see that there are images, even though they don't exist in the html. For example run this in the console of any extension background page:
$('<div>Hello, world!<img src="https://www.gravatar.com/avatar/fdc806d0a8834e57b2d9309849dea8cd"/></div>')
And you can see the image was loaded on the Application tab in dev tools, though it isn't in the html of the page when inspected and but it's visible on the network tab:
I assume that jquery is creating dom elements to use the browser's capabilities for finding elements, and that chrome is happily pre-fetching that image even though the element isn't on the page and the page will never be visible anyway, but it is causing me errors besides the extra network traffic.
I've tried disabling 'precache' in chrome://flags but that didn't work. For now I'm replacing <img with <noimg which seems to work but is not ideal:
$(text.replace(/<img /g, '<noimg '))
Is there a way to keep this from happening? Is there another library besides jQuery (like cheerio in node) that wouldn't actually create dom objects?
Use the built-in DOMParser to parse the HTML into a detached document, then use jQuery on that document object:
var doc = new DOMParser().parseFromString(yourHTMLstring, 'text/html');
$('.some.selector', doc).attr('foo', 'bar');
In case there may be relative links in the HTML, add a base element explicitly:
$(doc.head).append('<base href="' + realFullURL + '">')

Why can the background page be an html file?

In manifest.json, we specify our background page and can put an html or a js file for it. Since it is only a script that executes what sense does it make to have an html file for it?
I mean where is UI going to get shown anyway?
Similarly the devtools_page property has to be an html file. What sense does that make?
It will not be shown anywhere (that's the essence of "background"), but some elements on it make sense.
You can have an <audio> tag, and if you play it, it will be heard.
You can have an <iframe> with some other page loaded invisibly.
..and so on
As for devtools_page, it would actually be visible in the interface (as an extra panel in the DevTools)
It is possible that devtools_page must be an HTML file just for legacy reasons: it was not updated when manifest version 2 rolled out with changes to how background pages are specified. Still, the same arguments as above apply.
background_page is a legacy feature from the initial support of extensions in Chrome. background.scripts was added in Chrome 18. I can't speak for Google's original intentions but I'd guess that in the original design using an page felt more natural and would be less likely to confuse developers. Once they realized how many background_pages were just being used to load JavaScript it made sense to explicitly support that.

Mobile Safari fails to scroll to named anchor

I have a big SVG document here, containing a map of all the quests in a certain online game. Each quest node is inside a SVG <a> element, linking to a distinct named anchor in a big HTML document that loads in another tab, containing further details about that particular quest. This works exactly as desired in desktop Safari, and I'd expect it to work just as well in any browser that supports SVG at all since I'm using only the most basic form of linking, but it fails badly on Mobile Safari (iOS 6) - which is my single most important browser target, considering that the game in question is for the iPad. It only scrolls to the correct anchor on the initial load of the HTML page; clicking a different quest in the SVG tab will cause a switch to the HTML tab, and the hash (fragment ID) in the address bar changes, but the page doesn't auto-scroll.
This appears to be a known limitation in Mobile Safari - hash-only changes in the URL apparently used to force a page reload, and that got over-fixed such that nothing gets triggered at all now. The fixes I've found online all seem to be applicable only in cases where the URL change is being generated programatically, from within the same document, rather than static links from a different document.
Further details:
I've tried doing the named anchors in both the old <a name="..."> form, and the newer <h1 id="..."> form. No difference.
I've tried adding an onhashchange handler, to force the scrolling to take place, but the handler isn't being called at all (verified by putting an alert() in it).
I could presumably fix the problem by having each quest's details in a separate HTML file, but that would severely affect usability - with all the details in a single file, you can use your browser's Find feature to search through them all at once. (Also, deploying 1006 files to my web hosting after each update would be a bit of a pain...)
Anybody have an idea for a work-around?

Is it possible to create custom XUL elements from XPCOM or NPAPI?

I was wondering if it is possible to create a new XUL component via any available api, such as XPCOM or NPAPI, so we can use it our XUL files.
Let's say I wanted to clone the XULs vbox's components code and add a few modifications to it, so we could use our custom XUL component just like this:
<window>
<myvbox mycustomarg1="customValue"> Some content... </myvbox>
</window>
I know what XBL is and what is used for and it doesn't fit our need.
Any suggestion of how to achieve that?
Edit:
We need to create a browser component in Firefox as child of another browser object. The problem is some websites detect this child browser as iframe and we want to avoid this.
Thanks.
If the point is preventing a webpage loaded into a frame from messing with your XUL document then you should use <browser type="content"> - this establishes a security boundary between chrome and content which (among other things) prevents the content document from accessing its parent frame. It is important however that your XUL document itself is loaded as chrome and not content (by either being on top level or inside <browser type="chrome">). See https://developer.mozilla.org/en/XUL/Attribute/browser.type for documentation.

SVG with external images doesn't load them when embedded with <img> tag in browsers

I made the following observation:
If I create an svg image that references an external raster image via xlink:href and try to load the svg in browsers, the external images are only shown if I use the <object> tag, but not when using the <img> tag.
Rendering with the <object> tag is quite slow and not as clean as using the img tag for images so I was wondering if there's a way to make it work through the <img> tag.
At first I thought it doesn't work because of a same origin policy, but even if the referenced image is in the same directory and I reference it through its name only, it wont load.
Any ideas?
Are you using IE? IE doesnt recognize SVG anyway. Microsoft is always ten years behind, yet they are more popular and far more costly, for some reason. Name brand propaganda?
SVG loads in Firefox. Both as an XML document referenced directly in the URL, and also if you embed it into an XHTML (fully XML compliant) document with proper namespacing, the SVG should render properly. The great thing about this option is that DHTML can manipulate your SVG. Everything I said in this paragraph also applies to MathML, if youre curious.
Aside from that, SVG doesn't load from an image tag. I do believe Firefox is working on this upgrade, though. Im not entirely sure.
Using the object or embed tag is reasonable, I suppose... but one of my earlier fixes was to use an iframe. Embed an iframe in your html that references the complete SVG file. Using CSS you can make the iframe look flush with the rest of your document, appearing and acting like an image. Encased in a div or span tag, you can have onhover and onclick event handlers.
Using the image tag, your src can be a PHP file on server side. If properly coded and with the appropriate cgi apps, you can rasterize your SVG on server-side, and have that PNG data sent back to your image via the PHP src.
There's no particular reason <object> should be any slower to load than <img> apart from possibly the interaction aspect (img's are static while object's are fully interactive documents). The images inside the svg should load in both scenarios, so it sounds like a bug in the browser.
Could you post a link to your example?
I think you are at least 10 months behind...IE9 supports SVG, and pre-release versions (including a beta) have been out for quite a while. Check out www.ietestdrive.com to grab the platform preview - it's pretty good. In my opinion, parts of their SVG support are much better than Firefox currently (but they don't support SMIL yet).

Resources