Chrome Extension - How to execute a javascript file with button click function? - javascript

i read many documents about this but i couldnt figure out that. I need help about execute another js when button clicked.
test.js is my javascript file to execute. And in that file there is a just one line code like "alert("test.js executed!");
In my javascript file my click function is like that.
$("#src").click(function(){
alert("hi");
});
It's working well, i need to execute my "test.js" script. Like this:
$("#src").click(function(){
alert("hi");
$.getScript("javascript/test.js",function(){
})
.success(function(){
alert("success");
})
.error(function (){
alert("Failed to execute script");
});
});
But nothing happens. No errors aswell. How can i execute that script with click ?

That would fall under the use of eval, since that's exactly what getScript does.
This is not allowed by the default Chrome extension CSP and for a good reason.
You could argue that if the script is included with your extension, the security risk is non-existent,and you can override the CSP to allow that. It's bad and sloppy though.
Ideally, you want to simply include test.js with a <script> tag into the page, and call some function in it instead. Might need some modification on the file, but this is the proper way to do it.
If you absolutely need to execute the whole test.js every time (though there is no reason for it), create and append a <script> element with src appropriately set. This does not violate the CSP.

Related

How to trigger a js upon the exitting of the web page that created using ASP.NET MVC 5?

I already know this..
$(window).unload(function executebeforeexit() {
...........
});
and this
window.onbeforeunload = executebeforeexit;
function executebeforeexit()
{
................
}
and they did not work for me because they executed even I navigated via the page. This the whole code written in cshtml file.==> https://docs.google.com/document/d/13Huf8uWHTCJzJCWip3sJ4H22oN6rX-rZvgp70Pmd0kk/edit
I want to know how to solve this problem.
for help purpose it would be preferable to have your code shared in a public cloud links (ex.: http://jsbin.com/ , https://jsfiddle.net/ etc. )
usage of :
$(window).unload(callback)
is preferable to
window.onbeforeunload
If you can afford to have jquery loaded
But before going into details, please note that not all browser support having a callback on a page unloading and that it must be synchrone (async execution will never happen)
if you prefer not to use jquery for this purpose, please consider using
window.addEventListener('unload', callback)
It's more clean and allow to have multiples functions as a callback (as you can add multiple listeners) so you make sure your unload callback don't get overwrite somewhere else in your code.
If your page contain iframes or framesets, the listener might be placed on the frame itself if you require it

Firefox add-on declaring functions and use in content script

i am trying to write my first firefox add-on. the main problem seem s to be that i am also new to javascript. at the moment i have:
require('sdk/page-mod').PageMod({
include: ["*"],
contentScript: 'window.addEventListener("click", function(e) { alert("blub"); }, false);',
attachTo: ["existing", "top"]
});
(thx to the answer here.)
now i want to use a declared function instead of an anonymous one, but i cant get it to work:
require('sdk/page-mod').PageMod({
include: ["*"],
contentScript: 'window.addEventListener("click", function(e) { alert("blub"); }, false);',
attachTo: ["existing", "top"]
});
getImgData function (e) {
alert("blubber3");
}
the first problem is i get syntax error by just adding the function "missing ; before statement". But cfx doesn't tell me the wrong line. (Is there any useful tool for js editing with good syntax check/ content assist?)
So how to declare a function and use ist somewhere else in the script. At the end the function needs to get the target of click and parse it.
(i read the tutorials but thy all use anonymous functions :-P)
thx in advance
It's important to realize the separation between chrome scripts and content scripts. Chrome scripts are those that run with the same security privileges as Firefox - they have full access to Firefox and your computer. Content scripts are those that run with the same privileges as web pages. They can mess around with that web page, but are severely restricted otherwise. To maintain security, the way these two types of scripts can communicate is limited. You wouldn't want a web page to be able to call any function it wants in your extension's internal code!
Your main JS file (the one that includes require('sdk/page-mod')) is a chrome script. What you're injecting (contentScript) is (obviously) a content script. They can't communicate through a direct function call as you're doing.
If your getImgData function is something that can be done with normal web page privileges, you can move your definition of it to within the content script. If it requires additional privileges, you must have your content script communicate with your chrome script via the emit and on functions as described in the link above.
If you are going to make your content script any longer, I would recommend you separate it into its own file to make your life easier.

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.

defer script execution for some time

Is it possible, in javascript, to defer the execution of a self-execution function that resides at the top level closure? (For you to understand, jQuery uses this. It has a self-execution function at global scope)
My objective here is to make the whole external script to execute at a later time without deferring it's download, such that it downloads as soon as possible and executes after an event (I decide when that event happens).
I found this also:
https://developer.mozilla.org/en-US/docs/DOM/element.onbeforescriptexecute
Sounds like a "part 1" of what I want. If I cancel, the script is not executed. but then... How do I effectively execute it later?
Note1: I have absolutely no control over that external script, so I cannot change it.
Note2: Both me and who requested this does not care if there's slowness in IE due to stuff like this (yeah, true! (s)he's anti-IE like me)
Edit (additional information):
#SLaks The server sends the default headers that apache send (so-it-seems) plus a cache-control header ordering to cache for 12 hours.
From the POV of the rules about domains, it is cross-domain.
I'm not allowed to change the definitions about the other server. I can try to asking for it, though.
Unfortunately it's not possible to do with the <script> tag because you can't get the text of an external script included that way to wrap it in code to delay it. If you could, that would open up a whole new world of possibilities with Cross Site Request Forgery (CSRF).
However, you can fetch the script with an AJAX request as long as it's hosted at the same domain name. Then you can delay its execution.
$.ajax({
url: '/path/to/myscript.js',
success: function(data) {
// Replace this with whatever you're waiting for to delay it
$.ready(function() {
eval(data);
});
}
});
EDIT
I've never used $.getScript() myself since I use RequireJS for including scripts, so I don't know if it will help with what you need, but have a look at this: http://api.jquery.com/jQuery.getScript/
FYI
If you want to know what I'm talking about with the CSRF attacks, Check this out.

Debugging javascript code that comes as part of Ajax Response

So in my website, I use jquery to fetch data through ajax. AS part of the ajax response, some of the javascript code comes as well which is executed. The problem is how to debug this javascript in firebug or other tools. This is my experience so far:
putting debugger; doesn't work
For some javascript, can't set the breakpoint as that script is not yet loaded.
even if this new javascript calls some other function thats already loaded (i.e. i can see it in firebug and set a breakpoint), that breakpoint on that function is still not triggered
However, the javascript does executes normally and even things like console.log works but cant seem to debug it..
If you use Google Chrome, check out the answer of this question:
https://stackoverflow.com/a/10929430/482916
You need to add in the ajax-loaded JS scripts the following comment:
//# sourceURL=dynamicScript.js
where dynamicScript.js is the name of the script which will come up in the console.
I know Firebug and the IE developer tools will respect the debugger statement. So I would throw that onto the top of the response.
debugger;
func1();
func2();

Categories

Resources