简体   繁体   English

通过JavaScript从iframe获取src参数

[英]Get src parameters from iframe through javascript

I have a following iframe with different parameters such as time,query. 我有以下带有不同参数(例如时间,查询)的iframe。 I want to extract the parameters from this iframe through javascript so that I can replace the values of the selected parameters. 我想通过javascript从此iframe中提取参数,以便可以替换所选参数的值。 How can I do that? 我怎样才能做到这一点?

<iframe src="http://localhost:5601/#/dashboard/New-Dashboard?
embed&_g=(refreshInterval:(display:Off,pause:!f,section:0,value:0)
,time:(from:now-6M,mode:quick,to:now))&_a=(filters:!(),panels:!
((col:1,id:env,row:1,size_x:4,size_y:3,type:visualization),
(col:5,id:env-2,row:1,size_x:4,size_y:3,type:visualization),
(col:9,id:env-3,row:1,size_x:4,size_y:3,type:visualization)),
query:(query_string:(analyze_wildcard:!t,query:'*')),title:'New%20Dashboard')
" height="600" width="800" id="myframe"></iframe>

I see this working in two steps. 我看到此工作分两个步骤进行。 1) Grab your src string, and 2) parse out the parameter. 1)抓取您的src字符串,然后2)解析出该参数。

  1. With jQuery, this can be done simply with var frame_src = $('#myframe').attr('src'); 使用jQuery,只需使用var frame_src = $('#myframe').attr('src');

  2. Next, I recommend using regular expressions to pull out your parameters. 接下来,我建议使用正则表达式提取参数。 The easiest way to do this is to design your parameter names and values such that they fit a specific, easy to match pattern. 最简单的方法是设计参数名称和值,使其适合特定的,易于匹配的模式。

For example, you could set it up such that parameter name will be led by either a "?" 例如,您可以将其设置为以“?”开头的参数名称。 or a "&", and followed by a ":". 或“&”,后跟“:”。 They key value pair will end with either another "&" or the end of the string ("$"). 它们的键值对将以另一个“&”或字符串(“ $”)结尾。 The pattern would look something like this: 该模式如下所示:

var attr_name = "The attribute you're looking for";
var kvpair_pattern = new RegExp("[\?|&]" + attr_name + ":\w+[&|$]");

And you would extract the data with the exec() method. 然后,您将使用exec()方法提取数据。

var mydata = kvpair_pattern.exec(frame_src)[0];

Keep in mind, you will have the leading "?" 请记住,您将拥有领先的“?” or "&" with this method. 或使用此方法的“&”。 I don't know of a work-around other than stripping it off as an afterthought since JavaScript doesn't support look-behinds. 我不知道有一种解决方法,只是将其剥离作为事后的想法,因为JavaScript不支持后向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM