Add automatically running JS Code to the server

Source: Internet
Author: User

It is not a complicated task, but a serverCodeTo control the running of a JS function during client loading. But it took a long morning, the first thing was to use

Page. clientscript. registerclientscriptblock (typeof (string), "fomrjs", JS );

This JS block will be placed before </form> and run before window. onload. If it is not complex code, such as alert, there is no problem at all. However, the JS functions I use are just complicated, and errors are reported every time. Copy the code and move the JS block between </form> and </body>. Therefore, consider how to put JS blocks out of </form>.

Find a method that can be added to the

// Add head
Htmlgenericcontrol include2 = new htmlgenericcontrol ("script ");
Include2.attributes. Add ("type", "text/JavaScript ");
Include2.innerhtml = JS;
Page. header. Controls. Add (include2 );

However, you cannot access the body or document object. You can only access the form object, corresponding to the form tag or page. controls, but add the code to the </body> field.

I had to test the onload method, but I don't want to manually add onload to the page's body tag every time. I hope this event can be written and processed purely on the server. The result is still unable to be successful because the body tag cannot be accessed.

The final method is to use registerclientscriptblock to execute a code and specify the event processing as follows:

Page. clientscript. registerstartupscript (typeof (string), "fomrjs", "window. attachevent ('onload', function () {alertwin ('title dfadsa ', 'content here', 300,200) ;}", true );
Or

Page. clientscript. registerstartupscript (typeof (string), "fomrjs", "document. body. onload = function () {alertwin ('title dfadsa ', 'Here is the content', 300,200);} ", true );


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.