如何使用MSHTML解析onclick javascript事件参数?
我需要提取以下标记中定义的 onlick 事件中的 javascript 调用:
<div style="cursor: pointer;" onclick='javascript:start("a", "b", "code");'>Click Here</div></div>
这是我想要从 onclick 中提取为文本字符串的内容: 'javascript:start("a", "b", "代码");'
我是使用 MSHTML 的新手,这是我迄今为止尝试过的方法,但毫无进展。也许有更好的方法来做到这一点?
foreach (mshtml.IHTMLElement elm in (IHTMLElementCollection)doc.body.all)
{
if (elm.getAttribute("onclick", 0) != null)
{
if (elm.getAttribute("onclick", 0).ToString().Contains("javascript:start"))
{
Debug.WriteLine("Found!");
}
}
}
I need to extract the javascript call in the onlick event defined in the following markup:
<div style="cursor: pointer;" onclick='javascript:start("a", "b", "code");'>Click Here</div></div>
This is what I want to extract from onclick as a text string:
'javascript:start("a", "b", "code");'
I am a novice at using MSHTML and this is what I tried so far and I am getting nowhere. Maybe there is a better way to do this?
foreach (mshtml.IHTMLElement elm in (IHTMLElementCollection)doc.body.all)
{
if (elm.getAttribute("onclick", 0) != null)
{
if (elm.getAttribute("onclick", 0).ToString().Contains("javascript:start"))
{
Debug.WriteLine("Found!");
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想通了。只需检查元素的outerHTML。 elm.outerHTML.ToLower().Contains("javascript:start")
I figured it out. Just check the outerHTML of the element. elm.outerHTML.ToLower().Contains("javascript:start")
onclick 属性根本不应该包含“javascript:”。它不接受 javascript: URL 作为其值。它应该只包含 JavaScript 表达式。 (尽管如此,如果您确实包含“javascript:”,那么脚本引擎只会将其视为标签,不会产生任何不利影响)。
IE
正确
<
p onclick="javascript:alert('hello');"> ;这并不理想。
因此,假设正在解析的标记正确执行此操作,那么上面的代码不应检查是否包含字符串“javascript:”。它应该只是:
if (elm.getAttribute("onclick", 0).ToString().Contains("start"))
The onclick attribute should not contain "javascript:" at all. It doesn't accept a javascript: URL as its value. It should just contain javascript expressions. (Although, if you do include "javascript:", then it is just treated by the scripting engine as a label with no adverse effects).
i.e.
<p onclick="alert('hello');">This is correct</p>
<p onclick="javascript:alert('hello');">This is not ideal.</p>
So then assuming the markup being parsed does this correctly, then your code above should not check for the inclusion of the string "javascript:". It should just be:
if (elm.getAttribute("onclick", 0).ToString().Contains("start"))
获取此数据的另一种方法是通过 .getAttribute() 函数:
这假设“oHTMLDivElement”是 MSHTML.HTMLDivElement 对象。
Another way to get this data is through the .getAttribute() function:
This assumes that 'oHTMLDivElement' is an MSHTML.HTMLDivElement object.