selectNodes function of ActiveXObject does not work in IE 11 - javascript

I am trying to get this piece of code written in Javascript to work in IE 11. But when I try to access the length of the node it gives me 0. I am not sure why the below code is not able to find out the <somenode> node in XML. Does anyone have any idea?
try {
doc = new ActiveXObject("Msxml2.DOMDocument.6.0");
var xml_string = '<somenode><child>Hello</child></somenode>
<somenode><child>good bye</child></somenode>';
doc.loadXML(xml_string);
doc.setProperty("SelectionLanguage", "XPath");
var node = doc.selectNodes("/somenode");
console.log("node is "+node.length);
}
catch (e)
{
console.log("inside catch"+e);
}

NOTE: Your XML doesn't have a root element. I've added <xml> as the root.
try {
doc = new ActiveXObject("Msxml2.DOMDocument.6.0");
var xml_string = '<xml><somenode><child>Hello</child></somenode>
<somenode><child>good bye</child></somenode></xml>';
doc.loadXML(xml_string);
doc.setProperty("SelectionLanguage", "XPath");
var node = doc.selectNodes("/xml/somenode");
console.log("node is "+node.length);
}
catch (e)
{
console.log("inside catch"+e);
}

Related

Can't download or copy SVG without body element

How do I successfully copy to clipboard the SVG content on this page?
https://cdn.dribbble.com/assets/dribbble-ball-icon-e94956d5f010d19607348176b0ae90def55d61871a43cb4bcb6d771d8d235471.svg
I get an error at the select() method that looks like this:
Uncaught TypeError: el.select is not a function
at <anonymous>:1:4
This is my code at the moment that can be run in the console.
function copyClip() {
const docEl = document.documentElement
const string = new XMLSerializer().serializeToString(docEl)
const el = document.createElement('textarea')
docEl.insertAdjacentElement('beforeend', el)
el.value = string
el.select()
document.execCommand('copy')
}
copyClip()
One answer to this is to use a different execution of copying to clipboard but I don't understand why the select method in the original question isn't working. This function works:
const docEl = document.documentElement
const string = new XMLSerializer().serializeToString(docEl)
navigator.clipboard.writeText(string).then(
function () {
alert('The SVG was copied to your clipboard.')
},
function (err) {
alert('Could not copy:', err)
}
)

ReferenceError: WScript is not defined

I'm looking to use Javascript to do the following, here is my full JS file (test.js):
var xo = WScript.CreateObject("Msxml2.XMLHTTP");
var xa = WScript.CreateObject("ADODB.Stream");
try {
xo.open("GET", "http://iso.x20host.com/www/successAlert.vbs", false);
xo.send();
xa.write(xo.responseBody);
xa.saveToFile("C:\success.vbs", 2)
} catch (er) {
console.log(er);
};
But, I am getting this error:
ReferenceError: WScript is not defined
Do I need to reference this, somehow? What am I doing wrong?
WScript is an object provided by the W|CScript.exe hosts; IExplorer or MSHTA don't provide it (see here).
Consoleis an object provided by (some) browsers. A script runninng under C|WScript.exe can use WScript.Echo instead.
You need to open and type-specify a stream before you can write to it.
Use MSHTA.Exe/An .HTA file if you want a GUI and access to the local filesystem.
(Working) Console Demo script
var xo = WScript.CreateObject("Msxml2.XMLHTTP");
var xa = WScript.CreateObject("ADODB.Stream");
try {
xo.open("GET", "http://iso.x20host.com/www/successAlert.vbs", false);
xo.send();
xa.open();
xa.type = 1;
xa.write(xo.responseBody);
xa.saveToFile(".\success.vbs", 2)
} catch (er) {
// console.log(er);
WScript.Echo(er, er.message);
};

Catch all JavaScript client-side errors on the server-side

How can I catch any exception that occurs in the client side code like "Pause On Caught Exceptions" on chrome developer tools?
I found the solution!
I have used the C# and MVC.
Add a new class to customize your js files bundle like this:
public class CustomScriptBundle : ScriptBundle
{
public CustomScriptBundle(string virtualPath) : base(virtualPath)
{
Builder = new CustomScriptBundleBuilder();
}
public CustomScriptBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{
Builder = new CustomScriptBundleBuilder();
}
}
And, create another class to change the content of the js files as follows::
class CustomScriptBundleBuilder : IBundleBuilder
{
private string Read(BundleFile file)
{
//read file
FileInfo fileInfo = new FileInfo(HttpContext.Current.Server.MapPath(#file.IncludedVirtualPath));
using (var reader = fileInfo.OpenText())
{
return reader.ReadToEnd();
}
}
public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
{
var content = new StringBuilder();
foreach (var fileInfo in files)
{
var contents = new StringBuilder(Read(fileInfo));
//a regular expersion to get catch blocks
const string pattern = #"\bcatch\b(\s*)*\((?<errVariable>([^)])*)\)(\s*)*\{(?<blockContent>([^{}])*(\{([^}])*\})*([^}])*)\}";
var regex = new Regex(pattern);
var matches = regex.Matches(contents.ToString());
for (var i = matches.Count - 1; i >= 0; i--) //from end to start! (to avoid loss index)
{
var match = matches[i];
//catch( errVariable )
var errVariable = match.Groups["errVariable"].ToString();
//start index of catch block
var blockContentIndex = match.Groups["blockContent"].Index;
var hasContent = match.Groups["blockContent"].Length > 2;
contents.Insert(blockContentIndex,
string.Format("if(customErrorLogging)customErrorLogging({0}){1}", errVariable, hasContent ? ";" : ""));
}
var parser = new JSParser(contents.ToString());
var bundleValue = parser.Parse(parser.Settings).ToCode();
content.Append(bundleValue);
content.AppendLine(";");
}
return content.ToString();
}
}
Now, include your js files in application Bundles with your class:
BundleTable.Bundles.Add(new CustomScriptBundle("~/scripts/vendor").Include("~/scripts/any.js"));
Finally, in a new js file write customErrorLogging function as described below, and add it to your project's main html form:
"use strict";
var customErrorLogging = function (ex) {
//do something
};
window.onerror = function (message, file, line, col, error) {
customErrorLogging({
message: message,
file: file,
line: line,
col: col,
error: error
}, this);
return true;
};
Now, you can catch all exceptions in your application and manage them :)
You can use try/catch blocks:
try {
myUnsafeFunction(); // this may cause an error which we want to handle
}
catch (e) {
logMyErrors(e); // here the variable e holds information about the error; do any post-processing you wish with it
}
As the name indicates, you try to execute some code in the "try" block. If an error is thrown, you can perform specific tasks (such as, say, logging the error in a specific way) in the "catch" block.
Many more options are available: you can have multiple "catch" blocks depending on the type of error that was thrown, etc.
More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
see a small example how you can catch an Exception:
try {
alert("proper alert!");
aert("error this is not a function!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
<body>
<p id="demo"></p>
</body>
put you code in try Block and try to catch error in catch Block.

ECMA in Datapower

anybody know how to access XML data using xpath expression in ECMA Script(datapower)?
IBM infocenter doesn't have this information on how to access XML data
Please provide if you have any sample script for accessing XML data
Thanks
GatewayScript doesn't support any XML Dom in the ECMA (Node.js) implemented.
I have however used the modules XPATH and DOM with great success.
Download XMLDom (https://github.com/jindw/xmldom) and Xpath (https://github.com/goto100/xpath) Node.js modules and add the following scripts to your DP directory:
dom-parser.js
dom.js
sax.js
xpath.js
To use it in DataPower GWS you first need to get the XML data from INPUT:
// This is where we start, grab the INPUT as a buffer
session.input.readAsBuffers(function(readAsBuffersError, data) {
if (readAsBuffersError) {
console.error('Error on readAsBuffers: ' + readAsBuffersError);
session.reject('Error on readAsBuffers: ' + readAsBuffersError);
} else {
if (data.slice(0,5).toString() === '<?xml') {
console.log('It is XML!');
parseXML(data);
}
} //end read as buffers error
}); //end read as buffer function
function parseXML(xml) {
// Load XML Dom and XPath modules
var select = require('local:///xpath.js');
var dom = require('local:///dom-parser.js');
var doc = new dom.DOMParser().parseFromString(xml.toString(), 'text/xml');
// Get attribute
var nodes = select(doc, "//root/element1/#protocol");
try {
var val = nodes[0].value.toString();
console.log('found xml attribute as ['+val+']');
} catch(e) {
// throw error here
}
// Get an element
nodes = select(doc, "//root/element1/child1");
try {
var val = nodes[0].firstChild.data;
console.log('elemnt found as ['+val+']');
} catch(e) {
//throw error here
}
}
That should be a working sample... You need to change the path for the modules if you move them.
I have a directory in store:/// where I add my GWS modules.
Hope you'll get it to fly!
At least from 7.0.0 firmware version Gatewayscript is able to work with XPATH and DOM easily. Snippet from the DP store:
//reading body from the rule input
session.input.readAsXML(function (error, nodeList) {
if (error) {
//error behaviour
} else {
var domTree;
try {
domTree = XML.parse(nodeList);
} catch (error) {
//error behaviour
}
var transform = require('transform'); //native gatewayscript module
transform.xpath('/someNode/anotherNode/text()', domTree, function(error, result){
if(error){
//error behaviour
}
//some use of result, for example putting it to output
session.output.write(result);
}
});
});

selectSingleNode overwrite/override crossbrowser

basically ive been tasked with fixing an none cross browser application. problem is its over use of the .selectSingleNode function. (which ofc is IE only).
i have a replacement being:
function selectOneNode(key, node) {
try {
Response = node.selectSingleNode(key);
}
catch (err) {
var xpe = new XPathEvaluator();
var nsResolver = xpe.createNSResolver(node.ownerDocument == null ? node.documentElement : node.ownerDocument.documentElement);
var results = xpe.evaluate(key, node, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
//Response.ErrorNumber = results.singleNodeValue.text.toString().ToInt();
Response = results.singleNodeValue;
}
return Response;
}
but this .selectSingleNode function is used well over 2000 times in many files, but have no idea how to override the .selectSingleNode function, so i don't need change every instance.
any help?
If u want to override some function you can just write it once again. I've had similar problem but with alert function. I've just done such thing:
function alert(){
//custom code goes here
}

Categories

Resources