简体   繁体   中英

Visual studio 2015 javascript access to dom elements

In a Visual Studio 2015 "Javascript universal Windows" application I have this very simple code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />

    <!-- WinJS references -->
    <link href="WinJS/css/ui-dark.css" rel="stylesheet" />
    <script src="WinJS/js/base.js"></script>
    <script src="WinJS/js/ui.js"></script>

    <!-- aaaaa references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
</head>

<body class="win-type-body">

    <div id="myDiv">BEFORE</div>

    <script>            

        window.onload = function () {
            document.getElementById("myDiv").innerHTML = "AFTER";
        };


    </script>
</body>

</html>

If I run the application, choosing "Local machine" or any Windows Phone emulator, I see "BEFORE": the line that changes the innerHtml of the div is not executed.

Otherwise, if I execute the html file outside of Visual Studio, in a browser window, I see "AFTER": this is true for all browsers, with a little exception in the behavior of Internet Explorer 11: in this case I see the message "Internet explorer restricted this web page from running scripts or activex controls", and when I click "allow the content" I see "AFTER".

Why this very simple script does not work in Visual Studio? Is it a matter of security restrictions, like in IE? And why I don't see any message at all in Visual Studio about the issue? How can I solve this problem in Visual Studio?

I've tested your code. It's true but you should write your code inside of javascript files. Just move window.onload at the begining of the default.js.

It's not really an error, that's why VS 2015 won't signal it.

The fact is that inline scripts are not allowed in Universal Apps because it is a common cause of CSS (cross-site scripting) attacks.

See the first of the Remarks at the end of the link to Microsoft documentation.

Some workarounds are discussed here .

One possible cause could be the code inside js script tags overwriting the window.onload method. You seem to be using a mix of relative and absolute paths in the script tag includes. So when running outside visual studio these files might not get included so the window.onload is not overwritten. Some steps to debug would be:

  1. Check web developer console for errors, network errors etc. (From memory F12 in IE)
  2. Remove all other script tags and test.
  3. Try window.addEventListener("load", function{ }, false); instead of window.onload .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM