Thursday, November 22, 2007

Passing url parameters to webpart in SharePoint

Sometimes you may need to create a webpart page in SharePoint that it can use the parameters passed by url. But the "Page Viewer" webpart does not allow you to use the parameters in your webpart page url. I even tried to use SharePoint Designer 2007 to modify the page directly, but still does not work.

So I think why not directly use a "Content Editor" webpart? Because a content editor webpart allows you to embed javascript code in it. We can use an "iframe" which url is generated by javascript with url parameters from the webpart page.

Then I create a webpart page, insert in a content editor webpart, and then insert the following code in it:

<script type="text/javascript">
function getQueryStringRegExp(name)
{
var reg = new RegExp("(^|\\?|&)"+ name +"=([^&]*)(\\s|&|$)", "i");
if (reg.test(location.href)) return unescape(RegExp.$2.replace(/\+/g, " "));
return "";
}

document.write("<iframe src='http://www.yourdomain.com/index.php?test="
+ getQueryStringRegExp('test') + "' width=100% height=100%></iframe>");
</script>


The function getQueryStringRegExp is for retrieve parameter value from url, which is get from here:
http://www.codebit.cn/pub/html/javascript/tip/javascript_get_url_parameter/

9 comments:

Anonymous said...

Wow - thank you. I had an urgent need to do something like this, an excellent idea - got me out of trouble!

Anonymous said...

I need to do something similar. I need to open an infopath form within iframe but retrieve the id from the editform url and add this to the formurl. Any idea how I can do this?

Anonymous said...

Great solution! Thank you very much!

Anonymous said...

Excellent Solution! Thanks

Anonymous said...

Thank you a lot!!

Anonymous said...

I'm a newbie on sharepoint and I need to send a parameter from a form web part to a content editor web part. I built the form webpart with the parameter T1, however...how could I send it to the content editor?? I think that your post is the more near thing to my trouble...

Buzz Zhang said...

Hi, there,

I think you can not use a "form web part" to send parameter from one webpart to another. My suggestion is to create some javascript code in webpart A to "rewrite" characters in webpart B on the same page when a button in webpart A is clicked. Hope that can solve your problem.

Augustwind said...

When I put this in a Content Editor web part, I get this as I save:
"The HTML source you entered might have been modified"
and it totally screws up the script

Anonymous said...

Hi,I have to change page link dynamically on some anchor clicks ,So i have used javascript for passing source parameter to Iframe tag in html form web part ,the web part works .However when i save my web part ,all my settings tab of page as well as web part gets disabled and the browser shows me object not found error .Guys any idea why am i getting this error and how can i resolve it?

Search

Google