简体   繁体   中英

TypeError: Cannot find function getElementById in object

I am doing automation scripting and I need to read data from an iframe (to validate the content). In my java code

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("ECMAScript");
try
{
  scriptEngine.eval(new FileReader("readIFrameContent.js"));
}
catch (ScriptException e)
{
  e.printStackTrace();
}

and readIFrameContent.js is

function getContentFromIframe(iFrameName)
{
    var myIFrame = document.getElementById(iFrameName);
    var content = myIFrame.contentWindow.document.body.innerHTML;
    alert('content: ' + content);
}

But I get an error.

javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "document" is not defined. (#3) in at line number 3

So I googled for a solution and edited the function

function getContentFromIframe(iFrameName)
{
    var document = new Object();
    var myIFrame = document.getElementById(iFrameName);
    var content = myIFrame.contentWindow.document.body.innerHTML;
    alert('content: ' + content);
}

and now the error is

javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: TypeError:
Cannot find function getElementById in object [object Object]. (#4) in at line number 4

Suggestions please.

I think you don't need the statement var document = new Object(); Your code should work without this statement.

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