How can I detect server-side (c#, asp.net mvc) if the loaded page is within a iframe? Thanks
This is not possible, however.
<iframe src="mypage?iframe=yes"></iframe>
and then check serverside if the querystring contains iframe=yes
or with the Referer header send by the browser.
Use the following Code inside the form:
<asp:HiddenField ID="hfIsInIframe" runat="server" />
<script type="text/javascript">
var isInIFrame = (self != top);
$('#<%= hfIsInIframe.ClientID %>').val(isInIFrame);
</script>
Then you can check easily if it's an iFrame in the code-behind:
bool bIsInIFrame = (hfIsInIframe.Value == "true");
Tested and worked for me.
Edit: Please note that you require jQuery to run my code above. To run it without jQuery just use some code like the following (untested) code to set the value of the hidden field:
document.getElementById('<%= hfIsInIframe.ClientID %>').value = isInIFrame;
Edit 2: This only works when the page was loaded once. If someone have idea's to improve this, let me know. In my case I luckily only need the value after an postback.
There is no way of checking this that will fit your requirement of "secure" as stated in your comment on #WTP's answer.
I don't think the server-side can do this, so why not put a hidden control in your page that will be in the iframe? When the URL in the iframe loads, you can add some client-side code to set the hidden input to indicate you are in an iframe. The easiest check would be on the client-side in an onload method, like this:
// Set hidden input
someHiddenInput.value = self != top
It's more secure than the querystring, but it still might not be enough security for you.
My 2 cents.
Old question but why not a more simplistic approach like
var isFramed = self !== parent
Related
I have a checkbox in my formview which I want to access in JS to do some enable/disable for textboxes.
This is what I have:
<script type="text/javascript">
$(document).ready(function () {
$('#<%=FormView1.FindControl("chkMap").ClientID%>').change(function () {
if ($(this).is(":checked")) {
}
$('#textbox1').val($(this).is(':checked'));
});
});
With this code, nothing happens and no error is shown in firebug console. Am I doing something wrong? Thanks, Laziale
I have a few guesses. The first one is probably wrong but I had to point it out. The code you posted does not have an end script (</script>) tag. You should check that first.
Second guess is, for some reason <%=FormView1.FindControl("chkMap").ClientID%> this might not be outputting the ID of that control. Have you tried to 'view source' of that page and made sure that the ID is as it should be? Maybe you've changed the ID of that checkbox or something.
Third guess is the way you reference the textbox (#textbox). This is an ASP.NET WebForms page. Your checkbox is a server control (<asp:CheckBox ... />). Are you sure you haven't created the textbox like <asp:TextBox runat="server" ID="textbox1" />? If you have, you would need to write the code like:
$('#<%=FormView1.FindControl("textbox1").ClientID%>').val($(this).is(':checked'));
to reference that textbox control via JavaScript.
I'm suggesting all these because the JS code works fine. I've created a JSFiddle and tested it.
Here's the fiddle. link
I have a MasterPage which will appear in every page in the application and I'm trying to load a "LoginBox" which uses PageMethods inside a Div tag in this MasterPage
So far I have tried doing as I would do on a Content Page, tried converting it into a User Control and tried using a server side include (< !--#include file="LoginBox.aspx"-->)
None succeeded.
I can see with firebug that the webresources get loaded but the PageMethods javascript isn't created in any of those methods.
I am REALLY trying to avoid having to create a WebService for this, and moving the LoginBox is not an option, I would rather drop the MasterPage idea, but then maintenance would become hell.
I need ideas or a direction on this.
Any help is appreciated
I got it working successfully with an iframe loaded from javascript, to me it's an ugly solution, but still one. I'm open for better solutions
<script type="text/javascript">
(function () {
var e = document.createElement('iframe');
e.setAttribute("src", "LoginBox.aspx");
e.setAttribute("scrolling", "no");
e.setAttribute("frameborder", "0");
e.setAttribute("height", "73px");
e.setAttribute("width", "225px");
e.setAttribute("marginheight", "0px");
e.setAttribute("marginwidth", "0px");
e.async = true;
document.getElementById('loginboxd').appendChild(e);
} ());
</script>
Looks to me like you're mashing classic asp with ASP.NET
the point of user controls is to encapsulate exactly what you are doing here.
even then however you will find your attempts to componentize your code will still lead to a messy mess mess. consider moving over to ASP.NET MVC if you can. with that you can do far more suitable and cleaner things to keep your codebase clean.
How can I write JavaScript code in asp.net in code behind using C#?
For example:
I have click button event when I click the button I want to invoke this java script code:
alert("You pressed Me!");
I want to know how to use java script from code behind.
Actually, this is what you need:
string myScriptValue = "function callMe() {alert('You pressed Me!'); }";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "myScriptName", myScriptValue, true);
Copy all of javascript into string and then register it into your aspx page in code-behind. Then in aspx page, you can call the javascript function whenever you want. You should write this code in Page_Load method in C# page.
Have a look at the ScriptManager class' RegisterClientScriptBlock and RegisterStartupScript methods.
One way to put some javascript onto the page into a specific location do this:
ASP.Net
<script type="text/javascript">
<asp:Literal id="litScript" runat="server" />
</script>
C#
litScript.Text = "alert("Hello!");"
Of course, you can put anything in there, and I'd recommend a javascript library.
Using the Scriptmanager is also an option.
Not an answer, but a suggestion.
Mixing your js within your code-behind can come back to haunt you, I agree with Adrian Magdas.
Anytime you need to make a simple change/update to your javascript you'll have to re-build your project, which means re-deploying instead of simply pushing out a single .js file.
Something like:
btnSomething.ClientClick = "alert('You pressed me!');";
You might also want to read up on the ScriptManager control and outputting blocks of script.
The right answers usually is "You don't". It's better to define your code in a .js file and use jQuery to hook-up the desired events.
$(document).ready(function() {
$('#myBtn').click(function() {
alert('Handler for .click() called.');
});};
If you want to register a script that will be used in connection with an UpdatePanel (AJAX) use ScriptManager class as Sani Huttunen pointed.
Otherwise you should use the class ClientScriptManager (methods Page.ClientScript.RegisterClientScriptBlock or Page.ClientScript.RegisterStartupScript)
As other user pointed, normally registering a script on the code behind can and should be avoided. It's not a very nice practice and you should do it only in cases where you have no other option.
Response.Write("<script language='javascript'>alert('You pressed Me!');</script>");
I am wanting to use the Facebox plugin for JQuery but am having a few issues getting it running how I want. The div that houses the facebox content is created outside of the tag so even though I am loading up some web controls none of them are firing back to the server.
Has anyone dealt with this that can give me some pointers?
poking around the facebox.js I came across this line in the function init(settings)...
$('body').append($.facebox.settings.faceboxHtml)
I changed that to ...
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
and it loads up in the form tag, not sure yet if there are any side effects
You can use this code to register the PostBack event:
btn.OnClientClick = string.Format("{0}; $.facebox.close();",ClientScript.GetPostBackEventReference(btn, null));
this will let the button fires a PostBack.
Even after the :
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
change I found it problematic. When you look at the page source using firebug you see that all the html in the div assigned to be the facebox div is doubled up (repeated).
So all of those controls with supposed unique id's are doubled up on the page, that can't be good on the postback, i've decided putting asp.net web controls in a facebox is not a good idea.
I modified facbox.js to do this. Maybe there is a better solution but this works like a charm
Here what i did:
add two lines on top of facbox.js before '(function($)'
var willremove = '';
var willremovehtml = '';
find "reveal: function(data, klass) {" and add this lines before the first line of function.
willremove = data.attr('id')
willremovehtml = $('#'+willremove).html()
$('#'+willremove).html('')
find "close: function() {" and make it look like below.
close: function() {
$(document).trigger('close.facebox')
$('#'+willremove).html(willremovehtml)
willremovehtml = ''
willremove = ''
return false
}
I have run in to a bit of a problem and I have done a bit of digging, but struggling to come up with a conclusive answer/fix.
Basically, I have some javascript (created by a 3rd party) that does some whizzbang stuff to page elements to make them look pretty. The code works great on single pages (i.e. no master), however, when I try and apply the effects to a content page within a master, it does not work.
In short I have a master page which contains the main script reference. All pages will use the script, but the parameters passed to it will differ for the content pages.
Master Page Script Reference
<script src="scripts.js" language="javascript" type="text/javascript" />
Single Page
<script>
MakePretty("elementID");
</script>
As you can see, I need the reference in each page (hence it being in the master) but the actual elements I want to "MakePretty" will change dependant on content.
Content Pages
Now, due to the content page not having a <head> element, I have been using the following code to add it to the master pages <head> element:
HtmlGenericControl ctl = new HtmlGenericControl("script");
ctl.Attributes.Add("language", "javascript");
ctl.InnerHtml = #"MakePretty(""elementID"")";
Master.Page.Header.Controls.Add(ctl);
Now, this fails to work. However, if I replace with something simple like alert("HI!"), all works fine. So the code is being added OK, it just doesn't seem to always execute depending on what it is doing..
Now, having done some digging, I have learned that th content page's Load event is raised before the master pages, which may be having an effect, however, I thought the javascript on the page was all loaded/run at once?
Forgive me if this is a stupid question, but I am still relatively new to using javascript, especially in the master pages scenario.
How can I get content pages to call javascript code which is referenced in the Master page?
Thanks for any/all help on this guys, you will really be helping me out with this work problem.
NOTES:
RegisterStartupScript and the like does not seem to work at any level..
The control ID's are being set fine, even in the MasterPage environment and are rendering as expected.
Apologies if any of this is unclear, I am real tired so if need be please comment if a re-word/clarification is required.
Put a ContentPlaceHolder in the head section of the master page, then add a asp:Content control on the content page referring to the placeholder and put your script in that control. You can customize it for each page this way.
Also, the reference by ID may not be working because when you use Master Pages, the control IDs on the page are automatically created based on the container structure. So instead of "elementID" as expected, it may be outputting "ctl00_MainContentPlaceHolder_elementID" View your source or use firebug to inspect your form elements to see what the IDs outputted are.
Isn't it possible to do with clean javascript ?-)
-- just add something similar to this inside the body-tag:
<script type="text/javascript">
window.onload = function(){
MakePretty("elementID");
}
</script>
By the way the script-tag has to have an end-tag:
<script type="text/javascript" src="myScript.js"></script>
Why not use jQuery to find all the controls? Something like this:
$(document).ready(function(){
$("input[type='text'], input[type='radio'], input[type='checkbox'], select, textarea").each(function(){
MakePretty(this);
});
});
This way you'll get all elements on the page, you can wait until the page is ready (so you don't modify the DOM illigally). The jQuery selector can get the elements in a bit more of a specific format if you need (ie, add a root element, like the ID of the body div).
It'd also be best to modify the MakePretty method so it takes the element not the ID as the parameter to reduce processing overhead.
Once you use Master Pages, the ids of controls on the client side aren't what you think they are. You should use Control.ClientID when you generate the script.
When using master pages, you need to be careful with the html attribute ID, since .NET will modify this value as it needs to keep ids unique.
I would assume your javascript is applying css styles via ID, and when you are using master pages the ID is different than what is in your aspx. If you verify your javascript is always being added, your answer needs to take into account the following:
ALWAYS set your master page id in page load (this.ID = "myPrefix";)
Any HTML element in your master page will be prefixed by the master page id (i.e.: on the rendered page will be "myPrefix_myDiv")
Any HTML element in your content place holder id will be prefixed with an additional prefix (i.e. myPrefix_ContentPlaceHolderId1_myDiv)
Please let me know if I can clarify anything. Hope this helps!