Calling chrome.i18n.getMessage(...) from a content script - javascript

My Google Chome extension makes use of a content script declared in its manifest via:
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["js/jquery-1.6.1.min.js", "js/content.js"]
}
],
It also comes with a localization-related resource bundle in _locales/en.
Looking up a key using chrome.i18n.getMessage(...) works flawlessly from general extension code (i.e., in options.html), but it fails (i.e., does not return anything) when executed from js/content.js while that script is being run in the context of the regular web page.
Is this a general limitation (this Chrome bug may be related) or did someone manage to get this working?

You should be able to use chrome.i18n.getMessage(...) from content scripts. Try restarting the whole browser.
Currently running: Version 24.0.1297.0 dev-m
I was hit by this as well. I'm not sure about the original poster's scenario, but my problems were caused by the bug (http://code.google.com/p/chromium/issues/detail?id=53628), which was referenced in a reply in Thilo's bug report. The bug is that the reloading of messages.json is unreliable when reloading your extension from the Extensions manager page. I originally started with an empty messages.json and then added to it as I tried to make use of chrome.i18n.getMessage. I too received no errors, but didn't get my message as expected. As illogical as it sounds and being new to development in general, I thought this might be one of those APIs that can't run from content scripts. Luckily that wasn't the case.

I would say a bug report needs to be created.
It doesn't say anywhere that it is supposed to work, but it doesn't throw an error that chrome.i18n.getMessage isn't accessible from a content scripts either, as all other API calls do. So that's a bug already.
It would be a nice feature to have. I think they started implementing it but either forget or left it for better times. A bug report would be a good reminder.
Meanwhile, you can get localization strings from a background page through messaging. Perhaps send one request at the beginning of a content script requesting an array of all strings you will need.

The strings only get loaded once, when activating the extension.
When the function returns "" this just means, that the index wasn't found.
One just needs to go to "Chrome Extensions" disable and re-enable the extension.
Then the function returns the localized strings - just as expected # Chromium 31.

Related

Bug in Visual Studio 2015 package.appxmanifest for ms-appx-web in start page?

I'm creating a Javascript Windows 10 Universal app. It complained about using javascript inline with html-- due to having script tags inside my .html file.
"CSP14312: Resource violated directive 'script-src ms-appx: 'unsafe-eval'' in Host Defined Policy: inline script. Resource will be blocked."
So I did some research online and it turned out that I could avoid this error by doing two things:
Open package.appxmanifest:
add to start page:
StartPage="ms-appx-web:///index.html"
Add to package.appxmanifest:
<uap:ApplicationContentUriRules>
<uap:Rule Match="ms-appx-web:///" Type="include" WindowsRuntimeAccess="allowForWebOnly" /> </uap:ApplicationContentUriRules>
(You read this right: we need 3 slashes... ///)
Now this works great and my program is running now without the errors. But I noticed that if I change the start page via the GUI then it can't save it because it complains it's an illegal uri. So the only way I could do this was right-click the package.appxmanifest and choose "view code" and then do it through code. (Actually #2 above can only be done through code).
Maybe someone can clue me in, did I do something wrong? Here's a screenshot doing this through the GUI:
I saw a similar bug has been filed - when use the same uri format in manifest's Content URIs setting, same issue occurs. It's because the there is a rule checks whether the uri has a host. If the uri's host is null or empty, the uri validation fails.
Seems VS team is considering removing this rule, so I think it will be fixed in future release but I cannot say which update will have the fix.

Javascript in asp.net MVC... Beginner issue

I created an Asp.Net MVC Internet Aplication and in my Index view of the Home Controller I have this
This is the first line, before the script results.
<script type="text/javascript" src="~/Script/Teste.js"></script>
<br />
This line comes after the script.
In my Teste.js I have this:
document.write("Yes! I am now a JavaScript coder!");
But nothing happens. If I change the src attribute and put some random name src="aaaa", despite the fact "aaaa" doesnt exist, I get no error in runtime.
EDIT
Also, check your path again. The default MVC templates in VS create a folder called Scripts, not Script. ("~/Scripts/teste.js")
Per the comment below, this was not the root cause of the issue, but in other cases can easily bite new JavaScript developers.
Most likely, your document.write function is firing before the document is ready, leading to the appearance that nothing is happening. Try the following in your Teste.js file
window.onload = function ()
{
document.write("Yes! I am now a JavaScript coder!");
//or even better as a test
alert("This alert was called");
}
Check the source of your page as well, it could be the document is being written to, you just can't see it due to markup/page styling.
As for you second issue, there will be no 'Runtime Exception' thrown if you reference a non-existent file. If you are using tools like Firebug or Chrome's developer tools, you should see a request to http://siteDomain/Scripts/aaaa.js with a response of 404, not found.
You generally should avoid using document.write() unless you absolutely have to use it for some reason... I don't think I've ever come across such a situation, and write a lot of Javascript.
Try this:
1) Put this in your HTML:
<script src="/scripts/teste.js"></script>
2) Put this in your JS:
alert('Yes! I am now a JavaScript coder!');
3) Open Chrome since it makes it easy to look for external resources loading and open the Network tab in Developer Tools (click the menu button at top-right, Tools > Developer Tools, Network tab).
4) Run your project and copy/paste the URL in the browser that comes up into this Chrome window, and hit enter.
When your page loads one of 2 things will happen:
A) You'll get the alert box you wanted or
B) You'll find out why it isn't loading because the Network tab will show the browser attempting to fetch teste.js and failing in some fashion, for example a 404, which would indicate you've got a typo in the path, or the script isn't where you thought it was, etc.
Put the following line at the very end of your document. There should not be anything after. Then try to load the page.
<script type="text/javascript" src="~/Script/Teste.js"></script>
Also, try pressing F12 once the page loads to see the source. Check if you script is there.
In MVC, the tilde is used to refer to the root URL of your application. However, it cannot normally parse this information. If you write:
<script src="~/Script/Teste.js"></script>
The lookup will fail, because the ~ means nothing special in HTML. If you're using Razor as your view engine (not ASPX), you need to wrap that call in Url.Content like so:
<script src="#Url.Content(~/Script/Teste.js)"></script>
Doing this will ensure a valid URL is provided to the browser.
With that in mind, you need to check that you have the file name and folder name both correct. You also need to ensure that the file is being deployed with your application. You can do this my opening the properties panel while the file is selected in the Solution Explorer and pressing F4.

When accessing site from external network using IE JS/CSS(YUI) based UI is not working correctly

We have ASP.NET application in which we have used the YUI to generated the popup for user interface. Now when I amd testing the locally isntalled site the popups are comming correctctly withoug any error and also getting displayed correctly on all the browwsers (including IE 7/8/9).
However when the site is exposed on the server and i tried to test it from the outside network the YUI popup's are not getting genrated correclty like if some Javascript or CSS are not getting loaded or are cached. Generally Ctr+F5 does the trick to flush local cache and to fix the issue we have added query parameters xyz.css?v=10 trick. But its not working. Now this issue is showing only on the IE(6/7/8/9) and other browsers are working correctly. To check the issue i again logged into the production box and found that popup is appearing correctly on IE also.
Now i am not having clue how it could possibly happen. Does any one has came across anything like this? What could be the cause of the issue and how to fix it ?
Thanks
As far as I know, IE caches GET responses.
The xyz.css?v=10 trick is used when you want it to use cached CSS but only as long as it is the same version. Whenever you change something in the css you need to change the url (ie xyz.css?v=20).
If you want IE to NEVER use the cached css, you need the URL to look different everytime. you can do that by adding some timestamp to the url.
something like:
xyz.css?v=201201180600123
(201201180600123 is a timestamp)

Javascript debugging difficult as browser doesn't refresh the scripts!

I'm trying to debug a Javascript written in the Mootools framework. Right now I am developing a web application on top of Rails and my webserver is the rails s that boots WEBrick.
When I modify a particular tree.js file thats called with in one a mootools init script,
require: {
css: [MUI.path.plugins + 'tree/css/style.css'],
js: [MUI.path.plugins + 'tree/scripts/tree.js'],
onload: function(){
if (buildTree) buildTree('tree1');
}
},
the changes are not loaded as the headers being sent to the client are Last Modified: 10 July, 2010..... which is obviously not true since I just modified the file.
How do I get rid of this annoying caching. If I go directly to the script in my browser (Chrome) it doesn't show the changes until I hit refresh, but this doesn't fix my problem when I go back to my application and hit refresh, it still loads the pre-modified script.
This has happen to me also in FF, I think it is a cache header sent by the server or the browser itself.
Anyway a simple way to avoid this problem while in development is adding a random param to the file name of the script.
instead of calling 'tree/scripts/tree.js' use 'tree/scripts/tree.js?'+random that should invalidate all caches.
As frisco says, adding a random number in development does the trick but you will likely find that the problem still affects you production. You want to push new JavaScript changes to your users but can't until their browsers stop caching the file. In order to do this, just get the files mtime and add that as the random string. This will only change when the file is modified and so the JavaScript will be loaded from cache if it has not been changed or it will be loaded from the server, if it has.
PHP has the function filemtime but as I'm not familiar with Ruby, I'm afraid I can't help you further in that direction (sorry!). However, this answer seems to accomplish what you want.
Try the Ctrl+F5 trick. To avoid hitting browser cache.
More info here:
What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

Is "localStorage" in Firefox only working when the page is online?

So I'm toying around with HTML 5 and the localStorage and I'm noticing that my values only get stored when I run the page in Firefox on the local host (i.e. http://127.0.0.1:8000/test/index.html), but when I run the file locally (file:///C:/test/index.html) my values don't get stored. Safari 4 has no problems with both setups.
So does anybody know if this is by design -> DOM Storage on the Mozilla Developer Center
(Firefox 2 permitted access to storage
objects higher in the domain hierarchy
than the current document. This is no
longer allowed in Firefox 3, for
security reasons. In addition, this
proposed addition to HTML 5 has been
removed from the HTML 5 specification
in favor of localStorage, which is
implemented in Firefox 3.5.)
Or if there is a workaround?
I wonder because offline storage that works only online sounds silly :P
If anybody wonders, the code is as easy as it gets:
function save()
{
localStorage.setItem('foo','bar');
}
function load()
{
var test = localStorage.getItem('foo');
alert(test);
}
It seems a bug: Bug 507361 - localStorage doesn't work in file:/// documents
Hope is fixed soon!
2011-09-13: Bug fixed, implemented in 'Mozilla8'. I tested this with Firefox 8 and it works now.
Well, the linked document does say that
localStorage is the same as globalStorage[location.hostname], with the exception of being scoped to an HTML5 origin (scheme + hostname + non-standard port)
I don't want to claim that I understand 100% what that means, but the bit in brackets would suggest that the URL needs to have certain properties - in particular that the scheme and hostname are what Firefox considers an HTML 5 origin. I suspect that file:/// URLs don't match this, while your http://127.0.0.1/ does.
edit: Looking at the W3C's description of the Origin property, step 7 looks like it might be causing the problem. Depending on how the localStorage handling is implemented, it may be expecting a 3-tuple as returned by step 12, but for a file:// URL the return value may be just about anything.
So, er, I suppose it is by design. On reflection, chances are that this isn't really by design; there's no reason why localStorage shouldn't work for file:// URLs. It might just be a case of the output of one browser-specific implementation not matching the expectations of another.
As for workarounds, would globalStorage not do what you want here?
As of Oct 5 2020, localStorage on Firefox seems to be broken again. Try this:
Download Mozilla demo page: https://mdn.github.io/dom-examples/web-storage/
Change the animal/color to something other than default.
close the page's tab (or the browser).
Download the page again. It's back to defaults. (Firefox 81:0 et.al.)
Even worse, if you do step 1 & 2 above and then open another copy of the demo in a new tab, not only does the new tab not get the saved data, but the original demo page (refresh it) has gone back to the defaults; as though the new tab STEPPED on the saved data.

Categories

Resources