3

Don't be surprised if what I'm doing is completely wrong or if the solution is obvious.

<script type="text/vbscript">
    Function AddPrinter()
        Set objNetwork = CreateObject("WScript.Network")
        objNetwork.AddWindowsPrinterConnection "\\a2031slhsfile1\2031CAT-T113-HP4014dn"
        objNetwork.SetDefaultPrinter "\\a2031slhsfile1\2031CAT-T113-HP4014dn"
        MsgBox "The printer was added and set as the default printer."
    End Function
</script>

I added the above vbscript to an HTML document in the head section and one of the buttons has the following property:

onclick="AddPrinter()"

I didn't find much about this when searching on Google for an hour. What I did find didn't work. How does it know whether you're calling the function from javascript or vbscript or whatever anyway?

I get this error:

SCRIPT429: ActiveX component can't create object: 'WScript.Network'
4

3 回答 3

5

Your Internet Explorer security settings prevent the creation of the ActiveX control. You need to allow "initialize and script ActiveX controls not marked as safe for scripting".

于 2013-05-24T18:48:20.510 回答
2

Hmm, WScript.Network works just fine in IE, at least up to version 8. As about OnClick, its default assignation (whether run JavaScript or VBScript) depend on script content in the page. If your page has scripts in both languages (JavaScript and VBScript), then JavaScript is default, i.e.:

onClick="MyFunc()" 'is equal to:
onClick="javascript:MyFunc()"

In seach case you'll need to use explicit language modifier to run your VBScript.

onClick="vbscript:MyFunc()"

But if your page contain only VBScript then that not necessary.

<html>
  <head>
    <title>Example</title>
    <script type="text/vbscript">
      Sub Hello()
          Set objNetwork = CreateObject("WScript.Network")
          If IsObject(objNetwork) Then
              MsgBox "Its working"
              MsgBox "Computer Name = " & objNetwork.ComputerName
          Else
              MsgBox "Not working"
          End If
      End Sub
      Sub btnTest2_OnClick()
          Hello()
      End Sub
    </script>
  </head>
  <body>
    <button onClick="Hello()">Test 1</button>
    <input type="button" value="Test 2" id="btnTest2">
    <input type="button" value="Test 3" onClick="Hello()">
  </body>
</html>

P.S. And if you not change your IE security settings, as Ansgar Wiechers suggest then you'll need to confirm (on first click).

enter image description here

于 2013-05-24T19:19:34.513 回答
2

You may elect to bypass the security settings of the Internet Explorer completely by saving the file as an HTA rather than an HTML. HTA's are hyper-text applications that are written as htmls and use the Internet Explorer as a GUI, but are not restricted by the same security concerns as an HTML. the only change you need to make is change the file extension from *.html to *.hta.

于 2015-12-02T00:58:27.153 回答