Solved

'contentWindow.document is null' error

Posted on 2004-03-30
38
2,210 Views
Last Modified: 2011-10-03
Does anyone know more about this error and maybe how to fix it? It happens when I call button click from javascript: Form1.button1.click();

Thanks
0
Comment
Question by:gromul
  • 18
  • 13
  • 3
  • +2
38 Comments
 
LVL 7

Expert Comment

by:dante469
ID: 10720589
What is the submit action of the button???

Please provide some code :)...

Have Fun,
Dante
0
 

Author Comment

by:gromul
ID: 10720700
The javascript code which calls the button click:

Dim sString as System.Text.StringBuilder
sString = New System.Text.StringBuilder
sString.Append("<script language='Javascript'>")
sString.Append("var res= confirm('Are you sure you want to update this article?');")
sString.Append("if (res == 1) {" & vbCrLf)
sString.Append(" OurForm.txtValidateUpdate.value = 1;" & vbCrLf)
sString.Append(" OurForm.btnValidateUpdate.click();" & vbCrLf)
sString.Append("}" & vbCrLf)
sString.Append("</")
sString.Append("script>")
Page.RegisterStartupScript("ValidateUpdateScript", sString.ToString())

The button event:

Sub btnValidateUpdate_Click( ByVal Sender As Object, ByVal E As EventArgs )
   If txtValidateUpdate.Value = 1 Then
      ExecUpdate()
   End If
End Sub

And here are my hidden controls:

<input type="hidden" id="txtValidateUpdate" value="0" runat="server" />
<asp:Button
   ID="btnValidateUpdate"  
   OnClick="btnValidateUpdate_Click"
   Text="_"
   height="1"
   width="1"
   runat="server" />
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10722160
I get it to work fine if I change the id of the form element to be OurForm

I am using Codebehind but here is my ASPX page:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="test.aspx.vb" Inherits="SecurityBroker2.Web.test"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
      <HEAD>
            <title>test</title>
            <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
            <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
            <meta name="vs_defaultClientScript" content="JavaScript">
            <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body MS_POSITIONING="GridLayout">
            <form id="OurForm" method="post" runat="server">
                  <input type="hidden" id="txtValidateUpdate" value="0" runat="server" NAME="txtValidateUpdate">
                  <asp:Button ID="btnValidateUpdate" Text="_" height="1" width="1" runat="server" />
            </form>
      </body>
</HTML>

and here is the codebehind code:

Public Class test
    Inherits System.Web.UI.Page
    Protected WithEvents btnValidateUpdate As System.Web.UI.WebControls.Button
    Protected WithEvents txtValidateUpdate As System.Web.UI.HtmlControls.HtmlInputHidden

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim sString As System.Text.StringBuilder
        sString = New System.Text.StringBuilder()
        sString.Append("<script language='Javascript'>")
        sString.Append("var res= confirm('Are you sure you want to update this article?');")
        sString.Append("if (res == 1) {" & vbCrLf)
        sString.Append(" OurForm.txtValidateUpdate.value = 1;" & vbCrLf)
        sString.Append(" OurForm.btnValidateUpdate.click();" & vbCrLf)
        sString.Append("}" & vbCrLf)
        sString.Append("</")
        sString.Append("script>")
        Page.RegisterStartupScript("ValidateUpdateScript", sString.ToString())
    End Sub

    Private Sub btnValidateUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnValidateUpdate.Click
        If txtValidateUpdate.Value = 1 Then
            'ExecUpdate()
        End If
    End Sub

End Class

Hope this might shed some light.

James :-)
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10722177
Remember that you can only have one form element per page. In your JavaScript your controls sit under a document element called OurForm, which in this case will be the id of the form element/tag. In you first post you said that you were calling it from Form1.button1.click(); which implies that the form id is Form1 which is why your JavaScript will fail to work as it will not be able to find any document element called OurForm.

James :-)
0
 

Author Comment

by:gromul
ID: 10722268
What I have in this post is the actual code, and I call it OurForm.
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10722293
The code I posted above works fine when I ran it in Visual Studio 2002. I am not running it in a frameset, just a single ASPX page.

James :-)
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10722301
What else is going on on that page? Can you post the complete page code?

James :-)
0
 

Author Comment

by:gromul
ID: 10722348
I really can't post the complete code, maybe I would send it to your email. Could you post your code as a single aspx page?
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10722373
I can do that is you want. Mail it to jamesc(**remove**)@dumgal(**remove**).gov.uk

Thanks,

James :-)
0
 
LVL 28

Expert Comment

by:mmarinov
ID: 10722456
hi gromul,

what is actually the "contentWindow"? is it the name of the form or what?
can you post the aspx code ( the HTML code ) ?
and where do you receive the error ?

if culshaja doesn't help you you can send me the page through email too.

B..M
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10722470
He's right there is no occurance of contentWindow in you code anywhere. Are you sure that this page is raising the error?

James :-)
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10722478
Is the page in a frame or an Iframe? This seems to be what contentWindow is alluding to.

James :-)
0
 
LVL 28

Expert Comment

by:mmarinov
ID: 10722504
gromul , you have to post the hole code so the EE can help you
you can do it with such format

--everything before the form tag
<form tag
...
the line that invokes the javascript

..</form>
-- everything after the form tag

if there is other pages that are invloved in a way with this page you can post their html too
you don't have to post the compleate code of your code behind and every other elements from your aspx that are not invloved in the problem

B..G
0
 

Author Comment

by:gromul
ID: 10722525
I have no idea what contentWindow is, google returns just about 130 pages about contentWindow.document and nothing really useful. I guess it's some javascript stuff behind the scenes. In my code I use <frame> tag, not iframe.

Here's the complete error:
Line: 107
Char: 13
Error: 'contentWindow.document' is null or not an object
Code: 0
URL: ...

I'm trying to enter the debugger again, but turning off "disable script debuggin" isn't working.
0
 
LVL 28

Expert Comment

by:mmarinov
ID: 10722566
actually there is a property contentWindow

contentWindow Property

--------------------------------------------------------------------------------

Retrieves the window object of the specified frame or iframe.

so you have to check pages within the frames if there is a javascript line with contentWindow.document

B..M
0
 

Author Comment

by:gromul
ID: 10722707
I got the debugger working, and here's where it stops:

<form name="OurForm" method="post" action="supersearch.aspx" language="javascript" onsubmit="ValidatorOnSubmit();" id="OurForm" __smartNavEnabled="true">
<input type="hidden" name="__VIEWSTATE" value="dDw2MzYyNjc5Nzk7dDxwPGw8U3VwZXI/>
                                                                                          /\

The viewstate value is a lot longer (about ten rows) and it just selects few letters and numbers in the middle: TtOZXcgU2VhcmNoO1RvdGFsIEFydGljbGVzO0F

Now, if I turn off the smart navigation, then the highlighted part is onsubmit="ValidatorOnSubmit(); in the form tag.
0
 
LVL 7

Accepted Solution

by:
culshaja earned 500 total points
ID: 10722790
Funnily thats what I get with your code when I try bits of it. The interesting thing is that ValidatorOnSubmit does not exist in the WebUIValidation.js file

If I add the follwoing (gleaned fromMSDN) it seems to work:

            <script language="javascript">
<!--

var Page_ValidationActive = false;

function ValidatorOnSubmit() {
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
}

// -->
</script>

James :-)
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10722806
Another option is to set EnableClientScript = false on the validator control.

James :-)
0
 

Author Comment

by:gromul
ID: 10722847
I tried including the script but I still get the error. Can it be put directly in WebUIValidation.js file? As for the other solution, I have many validators, so for which ones do I have to set EnableClientScript = false?
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:gromul
ID: 10722895
James, could you send the code that you got working to my email? Thanks.
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10723169
I just built the follwoing fragment:

<HTML>
      <HEAD>
            <title>test</title>
            <meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR">
            <meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
            <meta content="JavaScript" name="vs_defaultClientScript">
            <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
            <script language="javascript">
<!--

var Page_ValidationActive = false;

function ValidatorOnSubmit() {
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
}

// -->
</script>
            <script language="javascript">
<!--
//*****************************************************************************************
// SUB:                  ValidateArticleID_Client
//
// DESCRIPTION:
// Validates the format of Article ID on the client side.
//*****************************************************************************************
function ValidateArticleIDClient( Sender, E ) {
      //## Get the ArticleID and trim any blank spaces
      var strArticleID = E.Value;
      strArticleID = strArticleID.replace( /^\s+|\s+$/g,"" );

      //## Check if ArticleID field is empty
      if( !strArticleID.length == 0 ) {
            var subStrings = strArticleID.split( "-" );

            //## Check if there are 3 substrings separated by dashes
            if( subStrings.length == 3 ){
                  var strYear = subStrings[ 0 ];
                  var strTopic = subStrings[ 1 ];
                  var strSystemID = subStrings[ 2 ];

                  var blnYear = false;
                  var blnTopic = false;
                  var blnSystemID = false;
      
                  //## Check year
                  if( !isNaN( strYear )){
                        blnYear = true;
                  } //end if

                  //## Check topic textbox
                  switch( strTopic.toUpperCase() ) {
                        case  "IT": blnTopic = true; break;
                        case  "HC": blnTopic = true; break;
                        case  "EC": blnTopic = true; break;
                        case  "EC": blnTopic = true; break;
                        case  "OR": blnTopic = true; break;  
                        case  "CS": blnTopic = true; break;
                        case  "MC": blnTopic = true; break;  
                        case  "SC": blnTopic = true; break;
                        case  "DV": blnTopic = true; break;  
                        case  "GC": blnTopic = true; break;
                        case  "AC": blnTopic = true; break;  
                        case  "GB": blnTopic = true; break;
                        case  "MN": blnTopic = true; break;
                        case  "WT": blnTopic = true; break;
                        case  "WD": blnTopic = true; break;
                        case  "OC": blnTopic = true; break;
                        default: blnTopic = false;
                  } //end switch
      
                  //## Check system ID textbox
                  if( !isNaN( strSystemID )){
                        blnSystemID = true;
                  } //end if
      
                  //## If all three substrings are valid, then Article ID format is valid; doesn't
                  //##            mean that an article with this ID actually exists in the database
                  if( blnYear && blnTopic && blnSystemID ){
                        E.IsValid = true;
                  } //end if
                  else {
                        E.IsValid = false;
                  } //end else
            } //end if
            else { //## If the number of strings isn't exactly 3, validation is false
                  E.IsValid = false;
            } //end else
      } //end if      
      else { //## If the ArticleID textbox is empty, validation is true
            E.IsValid = true;
      } //end else
} //End ValidateArticleIDClient

//-->
            </script>
      </HEAD>
      <body MS_POSITIONING="GridLayout">
            <form id="OurForm" method="post" runat="server">
                  <asp:customvalidator id="valArticleID" runat="server" ErrorMessage="Invalid Article ID Entry." OnServerValidate="ValidateArticleID_Server" ClientValidationFunction="ValidateArticleIDClient" ControlToValidate="txtArticleID" text="" EnableClientScript="False"></asp:customvalidator><br>
                  <asp:textbox id="txtArticleID" runat="server" width="110" textmode="SingleLine" maxlength="20"></asp:textbox><br>
                  <input id="txtValidateUpdate" type="hidden" value="0" name="txtValidateUpdate" runat="server">
                  <asp:button id="btnValidateUpdate" runat="server" width="1" height="1" Text="_"></asp:button></form>
      </body>
</HTML>

And it works ok.
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10723191
Did some more digging. If you include a rerquired field validator on the form as well, then the code is emitted the first time the page is generated, but it disappears on the postback. That JavAscript is the last code to be emitted, and if you do a postback without the injected JavaScript but with a button then it appears on the postback. I am not sure if its because the Javascript is causing the page to attempt to postback before the javascript is injected into the page or what? Its VERY bizarre.
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10723196
You could try and disable the customevalidator before you register your JavaScript, that might work.

James :-)
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10723229
More digging.....

If yo just have the customvalidator control on the page and submit the form using a button rather than invoking the button click by JavaScript like you are the following is emitted at the very bottom of the page:

<script language="javascript">
<!--
var Page_ValidationActive = false;
if (typeof(clientInformation) != "undefined" && clientInformation.appName.indexOf("Explorer") != -1) {
    if (typeof(Page_ValidationVer) == "undefined")
        alert("Unable to find script library '/aspnet_client/system_web/1_1_4322/WebUIValidation.js'. Try placing this file manually, or reinstall by running 'aspnet_regiis -c'.");
    else if (Page_ValidationVer != "125")
        alert("This page uses an incorrect version of WebUIValidation.js. The page expects version 125. The script library is " + Page_ValidationVer + ".");
    else
        ValidatorOnLoad();
}

function ValidatorOnSubmit() {
    if (Page_ValidationActive) {
        ValidatorCommonOnSubmit();
    }
}
// -->
</script>

If you use your JavaScript then the HTML document is not completely generated and ends before even the form tage is closed - directly after the JavaScript is emitted that you want to emit for the update confirm. It seems to validate what I said above about your code stopping the page being completely generated.

James :-)
0
 
LVL 7

Expert Comment

by:dante469
ID: 10724519
I will accept 500 points and you do what you want as far as bonus points :)....

The following works for me and I would recommend you start with something very simple like this and then build/modify until it breaks...  Also PLS remember that JavaScript IS case sensitive...  function Dog is not the same as function DOG....

Stick with me and we will make this work!!!

Have Fun,
Dante

codebehind ---->>  Please notice I put withing PostBack code to prevent from asking over & over...

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not IsPostBack Then
            Dim sString As System.Text.StringBuilder
            sString = New System.Text.StringBuilder
            sString.Append("<script language='Javascript'>")
            sString.Append("var res= confirm('Are you sure you want to update this article?');")
            sString.Append("if (res == 1) {" & vbCrLf)
            sString.Append(" OurForm.txtValidateUpdate.value = 1;" & vbCrLf)
            sString.Append(" OurForm.btnValidateUpdate.click();" & vbCrLf)
            sString.Append("}" & vbCrLf)
            sString.Append("</")
            sString.Append("script>")
            Page.RegisterStartupScript("ValidateUpdateScript", sString.ToString())
        End If
    End Sub

    Private Sub btnValidateUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnValidateUpdate.Click
        If txtValidateUpdate.Value = 1 Then
            'ExecUpdate()
        End If
    End Sub

.aspx----->

<body MS_POSITIONING="GridLayout">
<form id="OurForm" method="post" runat="server">
      <input type="hidden" id="txtValidateUpdate" value="0" runat="server" NAME="txtValidateUpdate">
      <asp:Button ID="btnValidateUpdate" Text="_" height="1" width="1" runat="server" />
</form>
</body>

0
 

Author Comment

by:gromul
ID: 10729814
I'm back.

@James: So what you are saying is that my custom validation script is causing all the problems?
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10730345
Its not your custom validation script. It is the script hat you register as the StartUp Script that asks if you really want to update and then issues the button click command.

Why not replace the webforas button that you click that causes the postback to inject the javascrit to be an HTML button that pops up your message and then issues the button click command rather than doing a postabck and injecting the JavaScript as a startup script?

James :-)
0
 

Author Comment

by:gromul
ID: 10730431
You mean doing something like this? :
myDeleteButton.Attributes.Add( "onclick", "return confirm('Are you sure you want to delete this article from the database?');" )

If yes, that's not what I want. In that case confirmation comes before validation, which doesn't make sense. If something is wrong, the user should be notified of it before asking about confirmation.
0
 

Author Comment

by:gromul
ID: 10730453
James, I wasn't able to try out all your suggestions, so could you be more specific about these?

>Another option is to set EnableClientScript = false on the validator control.
Which validator? A specific one or all of them?

>You could try and disable the customevalidator before you register your JavaScript, that might work.
Disable it somewhere in code, then enable it again? I tried removing it altogether but that didn't help.
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10730895
The problem is that all of the validators need this routine not just the one that is causing the issue. Is there any way that you could split up this page into mutliple pages? That way you might be able to keep the code more manageable and so pinpoint the exact way to solve the issue?

Another option is not to register the script as the start up script but to use a literal control that you put at the bottom of the page, and set the text property to be a call to the confirm function. This might allow the validators to emit their code beforehand. Another option is to also emit the code that I posted above as being emitted by the validators in a literal control, that way its guaranteed to be there.

James :-)
0
 

Author Comment

by:gromul
ID: 10730951
I kept deleting the code and was still getting the same error. I finally removed the SmartNavigation=true and it worked.

James: The javascript with ValidatorOnSubmit that you posted helped: with that and without stupid smart navigation I don't get any errors. You mentioned you found that on msdn. Do you by any chance still have the link?

Anyways, all that remains is to find something like smart navigation that actually works. The points go to you. As some people complained about my method of attracting attention to my problem, I'll post additional 8 obvious questions about asp.net so that you can collect your reward :)

Thanks again for all your help!
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10730953
Hmm, scratch that idea. I added a literal to a form as the very bottom control and instead of setting the start up script to be your script I set the literals text property to your JavaScript. It now finds the function but errors within the WebUIValidation.js file. I really do think that you need to find a way to get the user to click a button to fire this code.

James :-)
0
 

Author Comment

by:gromul
ID: 10730968
Can you post a comment to my 5000 points post so that I can use that one also.
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10731045
Where is it?

James :-)
0
 
LVL 7

Expert Comment

by:culshaja
ID: 10731061
0
 

Author Comment

by:gromul
ID: 10731101
0
 

Expert Comment

by:nasiry
ID: 10957223
Any answers yet?  to the contentWindow.document error.......   I have the same problem


cheers
0
 

Expert Comment

by:nasiry
ID: 10957816
I think I have finally found the solution although I might have other implications.

If I set SmartNavigation = “false” the error does not happen.

If you look at SmartNav.js under aspnet_client\system_web\1_1_4322(version)  
Line 106/107

This is the code that causes the bug.   I think…    It does not do any harm.  But it works….
So I inserted

if (sn.hif != null)
        {
 try {

            var hif = sn.hif;
            sn.hifName = "__hifSmartNav" + (new Date()).getTime();
            frames["__hifSmartNav"].name = sn.hifName;
            sn.hifDoc = hif.contentWindow.document;
}
catch (e)

{ return;
}

cheers.... everybody-  do not blame  the Validation?????
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now