Right now my javascript looks like this :
testStackData.addOrUpdateHeader("username", "vikas test", 1);
testStackData.addOrUpdateHeader("testHeader", testStackData.priorResults.responseBody.cars[0].name, 1);
testStackData.addOrUpdateVariable("carNameTest", "variable updated from pre script", 1);
testStackData.stepError.haveError = false;
return testStackData
Now I need to create an Objective-C function addOrUpdateHeader
or addOrUpdateVariable
as mentioned in javascript.
But I am confused as how to call these functions.
I finally got my javascript code running my application with the help of Javascript core framework.
I created json string with my javascript functions embedded in the string itself. As javascript is lose in its definitions, it allowed the calling and execution of the functions effectively.
Moving on to the code, I created separate function for addOrUpdateHeader addOrUpdateVariable
The functions read as follows :
"addOrUpdateHeader" :
function(headerName, headerValue, trackHistory){
if(this.projectServers.projectServerDefaultHeaders.length>0) {
var index ;
var isHeaderNameExists = false;
for(var h =0; h<this.projectServers.projectServerDefaultHeaders.length;h++) {
if(this.projectServers.projectServerDefaultHeaders[h].headerName === headerName) {
index=h;
isHeaderNameExists = true;
break;
} }
if(isHeaderNameExists) {
this.projectServers.projectServerDefaultHeaders[index].headerValue = headerValue;
}
else {
this.projectServers.projectServerDefaultHeaders.push({
headerName : headerName,
headerValue : headerValue,
projectServerDefaultHeaderId : '',
trackHistory : trackHistory
});
} } },
"addOrUpdateVariable" : function(variableName, variableValue){
if(this.projectServers.projectServerDefaultVariables.length>0) {
var index ;
var isVariableNameExists = false;
for(var v =0; v<this.projectServers.projectServerDefaultVariables.length;v++) {
if(this.projectServers.projectServerDefaultVariables[v].variableName === variableName) {
index=v;
isVariableNameExists = true;
break;
} }
if(isVariableNameExists) {
this.projectServers.projectServerDefaultVariables[index].variableValue = variableValue;
}
else {
this.projectServers.projectServerDefaultVariables.push({
variableName : variableName,
variableValue : variableValue,
projectServerDefaultVariableId : ''
});
}}
}
and then used javascript core framework's JSContext to do the required functionality with the help of following code
JSContext *context = [[JSContext alloc] init];
context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
NSLog(@"[%@:%@:%@] %@\n%@", exception[@"sourceURL"], exception[@"line"], exception[@"column"], exception, [exception[@"stack"] toObject]);
};
[context evaluateScript:testStackData];
NSString * jsCode = [NSString stringWithFormat:@"var prescript = function (testStackData) {%@}",script];
[context evaluateScript:jsCode];
JSValue * ret = [context evaluateScript:@"prescript(testStackData);"];
here testStackData is my json string