Bookmarklet… meh

Getting tired of all the EVO/Android/iPhone love Jake’s been spewing lately? How about something a bit more dry and developery?  As promised in a prior post, here’s a more technical writeup of how I built the WebCenter sharing bookmarklet.  I was hesitant to write about this because it’s not like writing a bookmarklet is new and interesting… there are tons of tutorials on the web after all.  But as with everything, writing about it will make me appreciate the work I put into it more, I suppose.

Building a bookmarklet is pretty simple.  The basic idea is that a user clicks on the bookmark to execute some javascript to do what you want.  Creating a sharing bookmarklet can be a bit of a challenge depending on the implementation path you take. You can take a look at the various approaches by testing out a service called Shareaholic, a service that aggregates a bunch of sharing tools together as a Chrome extension or Firefox addon.  The simplest strategy for a sharing bookmarklet is to launch a new window/tab like Facebook or Digg, but personally, I’m not a fan of launching new windows so I decided to take a different approach.  Other sharing bookmarklets are “inserted” inside of the page you’re currently browsing.  Google Reader‘s and Posterous‘ bookmarklets are good examples of this. There are a few simple tricks necessary in order to build a bookmarklet like this.  Let’s use the following diagram for reference:

There are a few pieces to that make this bookmarklet possible:

  • Javascript to execute on the foreign page (bookmarklet.js) — this is injected by the bookmarklet itself through a script tag insertion.
  • Content iframe originating from the domain you’re sharing to (bookmarklet.html, #3 in the diagram above) — this is necessary because our bookmarklet needs to interact with a REST API on the domain where the user will be sharing to (in this case, the host/domain where WebCenter).
  • Proxy iframe (#4 in the diagram above) — this iframe is hidden off of the screen and is used simply to trigger events that happen on the parent.  I’ll go into more detail as to why this is needed later.

Here’s the flow:

  1. User triggers the bookmarklet (an inline javascript in an anchor link that a user adds to their bookmarks bar).  Upon execution, a new script tag is inserted into the foreign page and does the following:
    1. Inserts a stylesheet to the page defining the style of the dialog box we’re going to create (#2).
    2. Defines a div container for us to insert our DOM elements into which makes it easier for cleanup when after the bookmarklet is used.
    3. Inserts the content iframe (#3) which points to bookmarklet.html on the WebCenter host.
    4. Inserts the proxy iframe (#4) which points to proxy_frame.html on the WebCenter host.
  2. At this point, the sharing dialog window has been initialized and the iframes have been rendered.  Our bookmarklet communicates with the WebCenter REST API directly (#3).  Before presenting the user with the “publisher” (sharing textarea), we need to determine if the user can access the REST API.  Since our bookmarklet app is hosted on the same domain as the WebCenter app, we don’t can trigger the SSO system to authenticate the user if it’s needed (no fancy OAuth needed — good thing because WebCenter doesn’t support OAuth yet).  Upon a successful SSO authentication, the iframe in #3 is reloaded and the REST API is called in order to paint the rest of the form.
  3. The only interaction left is when the user clicks the “Share” button.  The Share button is purposefully inserted on the host page (not the iframe in #3).  The reason for this is the share button will need to be able to trigger the dialog to close and also clean up all of the HTML that was inserted onto the page.  You can’t do that if the button is inside the #3 iframe.  However, this causes us another issue.  How do we trigger the form submission in iFrame #3?  Because of cross domain rules, you can’t trigger an event in another frame that’s from a separate domain.  Enter iFrame #4, the proxy_frame.html.  Before I explain how this works, go read Michael Mahemoff‘s excellent article about Cross-Domain Communication with iFrames — the technique I use is the “Window Size Monitoring” hack.  The hack works like this…
    1. The main page (i.e., main parent) creates two iframes (#3 and #4), both of which reside on the same domain, but not necessarily the same domain as its parent.
    2. The first iframe contains the actual iframe you want the user to interact with (#3).  The second iframe is the “proxy” iframe (#4).  The proxy iframe’s purpose is to respond to events that the main parent triggers.
    3. When these trigger is executed, the proxy iframe will execute some javascript in it’s sibling iframe (#3).  But how does the main parent trigger an event on the proxy iframe which resides on a different domain, you ask?  iframes are like little windows within a larger window.  They can be resized.  One of the events a window can respond to is a “resize” event.  So, the trick is to hide this proxy iframe out of view from the user (position:absolute;top:-9999px;width:0;height:0). In the proxy_frame.html page, add an event listener on the window that listens for “resize” events:

So, that’s the gist of it.  Questions… ask below.

AboutRich Manalang

a.k.a.: manalang

25 comments

  1. Thanks for the post. Out of curiosity, how are you managing the closing of the bookmarklet. I have two external buttons adjacent to the content iframe: save and close. Close is easy because it can just remove the bookmarklet container div from the dom and nothing else needs to happen. But If I want to go ahead and process the action, which in this case is a form post within the content iframe, I have to trigger the resize of the proxy which sends the action to the content iFrame, and then still follow up and remove the container. If I immediately call remove() on the container, the iframe action never happens because it was closed too fast.

  2. Functionally, when we added the ability to post without the link of the page you're current on, we also had to add a confirmation message with a close function. Initially, once you clicked Share, the bookmarklet window disappeared on its own.

    So, I guess the guys can answer your question, even though we went away from that approach.

    Hoping Rich will see this and add relevant technical details.

  3. We opted for the first option you mentioned. Because our bookmarklet can be injected to any site on any domain, there's no way to set the proxy on the parent. So, we've opted for the simple “close” button approach on the parent and detached any events from the submit button… this forces the user to “close” the bookmarklet after they've submitted. This seems to be the popular choice.

  4. Thanks for the replies. Ideally, I'd like to have the bookmarklet window close after the action has completed, without requiring a second click after the action has completed. I've seen it done but haven't got a handle on how yet. Cheers.

  5. The way to do that is to put your submit button on the parent. When the submit button is pressed, send a message to the child frame to submit the content (through the proxy), then you can close the window after the callback has returned.

  6. На форуме медицинском наткнулся. которые то висят, то не грузятся. ЕГИСЗ — сидишь и не знаешь, что делать. Электронный рецепт — что для этого нужно. Вся информация доступна здесь: детская телемедицина https://cartripshop.ru И про ЕГИСЗ новости для пациентов. Но лучше знать, куда обращаться.

  7. Племянник жены в стоматологии ассистентом. Все стали жаловаться на перемены. Цифровое здравоохранение — говорили, что телемедицина теперь не роскошь. Электронный рецепт — и больничный не закроешь. Можете ознакомиться по ссылке: телемедицина для водителей телемедицина для водителей И про Техподдержку ЕГИСЗ для поликлиник. Кто не успел разобраться.

  8. Двоюродный брат в Минздраве служит. Собирались недавно за столом. Аккредитация медицинских работников ЕГИСЗ — раньше было проще. Телемедицина консультация — и каждый медик должен уметь. Советую глянуть источник: телемедицина что это такое простыми телемедицина что это такое простыми И про Искусственный интеллект в медицине для всех, кто в сфере здравоохранения. Система не будет ждать.

  9. По радио передавали. и всё больше электронных сервисов. Цифровое здравоохранение — и врачам приходится учиться работать по-новому. Электронный рецепт — об этом говорят на каждом углу. Можете ознакомиться по ссылке: егисз выписка аккредитации егисз выписка аккредитации И про Портал НМО для пациентов. Тема интересная.

  10. С таксистом разговорился по дороге. Тема одна и та же. ЕГИСЗ — кто-то недавно записывался к врачу. Телемедицина как воспользоваться — и не всегда есть, кому их задать. Вся информация доступна здесь: егисз новости егисз новости И про ЕГИСЗ Росминздрав для врачей. Тот рискует остаться за бортом.

  11. Пока сидел в очереди, услышал разговор. Одни ругают новые системы. ЕМИАС — кто-то считает это лишней бюрократией. Телемедицина консультация — это уже часть повседневной работы. Советую глянуть источник: протоколы егисз https://foodloversnet.ru Там и про Порталы НМО для пациентов. Спорить можно долго.

  12. Наткнулся на интересную тему. Оказывается, цифровизация в медицине. ЕГИСЗ — раньше врач писал от руки. Электронный рецепт — а врач видит всю историю болезни. Можете ознакомиться по ссылке: система егисз система егисз И про Центр телемедицины для больниц. Кто ещё не в теме.

  13. Невестка в детской поликлинике педиатром. Спрашивал у них про работу. Цифровое здравоохранение — раньше был бумажный журнал и всё. Электронный рецепт — где каждый шаг регламентирован. Вся информация доступна здесь: как выглядит электронный рецепт как выглядит электронный рецепт И про Медико-социальную экспертизу в ЕМИАС для врачей. Главное — не паниковать.

  14. Когда мы поняли, что обычная школа не подходит — мы задумались об альтернативе. Мы долго сомневались, но решили рискнуть. дистанционное обучение — это оказалось удобнее, чем мы думали. Все материалы доступны в личном кабинете. И главное — никакого стресса из-за дороги и ранних подъёмов. Рекомендую всем, кто ищет гибкий формат обучения. онлайн школа в москве онлайн школа в москве Сохраните, поделитесь, не потеряйте для столицы. Это удобно, эффективно и современно. Школа онлайн — образование без границ!

  15. Mostly a reader, rarely post, thought I would drop how I pick an online casino these days. After trying maybe a dozen sites I stopped trusting the big banners.

    Licence comes first for me: find the licence number and look it up, and whether they actually accept players from your country. Next come deposits and withdrawals: card, e-wallets and bank transfer should all be there, and there should be no weird fees on cashouts.

    Never judge a site by the bonus alone. Anything above 40x rollover is a red flag for me, and live tables often do not count at all. A useful overview with bonus rules, app info and payment methods is here read more and it saved me some time.

    I play almost only on my phone, so I check how the lobby works on a small screen. Ask support one simple question first: slow or scripted answers usually mean trouble later.

    Anyway, that is my routine. Set a budget and stick to it.

  16. Been reading this board for a while, thought I would drop how I pick an online casino these days. After getting burned once or twice I stopped going by ads alone.

    First thing is the licence: check who regulates the site, because some sites quietly block certain regions. Then payments: card, e-wallets and bank transfer should all be there, and cashout times should be listed up front.

    Bonuses are the tricky part. Anything above 40x rollover is a red flag for me, and live tables often do not count at all. A useful overview with bonus rules, app info and payment methods can be found here Smash Casino bonus so you know what you are signing up for.

    On mobile I mostly use the browser version, so I check how the lobby works on a small screen. Test the live chat before depositing: a real human reply beats a bot loop.

    Anyway, that is my routine. Only play with money you can afford to lose.

  17. Need reliable car rental options at HPN Airport? We’ve got you covered for premium vehicles with great rates.

    Browse top-rated HPN car rental companies and reserve your perfect ride with ease. white plains airport rental cars https://car-rental-hpn-bfk.com

    Don’t overpay for airport car rentals – these insider tips will save you money. Perfect for an SUV, there’s options for every budget.

  18. Been reading this board for a while, thought I would drop what I look at before signing up anywhere. After trying maybe a dozen sites I stopped going by ads alone.

    First thing is the licence: see which authority is listed in the footer, and if your country is on the allowed list. Then payments: card, e-wallets and bank transfer should all be there, and cashout times should be listed up front.

    The welcome offer is where most people get caught. Wagering of 35x or 40x is normal, and live tables often do not count at all. A useful overview with bonus rules, app info and payment methods is here Trino Casino app before you deposit anything.

    Most of my sessions are on mobile, and a good site loads fast and does not log you out every five minutes. Test the live chat before depositing: slow or scripted answers usually mean trouble later.

    Anyway, that is my routine. Only play with money you can afford to lose.

  19. Mostly a reader, rarely post, so here is how I pick an online casino these days. After trying maybe a dozen sites I stopped going by ads alone.

    I always start with licensing: see which authority is listed in the footer, and if your country is on the allowed list. Next come deposits and withdrawals: crypto is a plus but not a must, and cashout times should be listed up front.

    The welcome offer is where most people get caught. Wagering of 35x or 40x is normal, and live tables often do not count at all. A decent independent write-up with the current terms is worth a read here lottoland so you know what you are signing up for.

    On mobile I mostly use the browser version, and a good site loads fast and does not log you out every five minutes. Ask support one simple question first: a real human reply beats a bot loop.

    Hope this helps someone. Set a budget and stick to it.

  20. Mostly a reader, rarely post, but I figured I would share my short checklist for choosing a casino site. After getting burned once or twice I stopped going by ads alone.

    First thing is the licence: see which authority is listed in the footer, and if your country is on the allowed list. Then payments: I want at least one fast e-wallet option, and the withdrawal limits need to be written clearly.

    The welcome offer is where most people get caught. Wagering of 35x or 40x is normal, and live tables often do not count at all. A decent independent write-up with the current terms is here Pure Casino and it saved me some time.

    Most of my sessions are on mobile, so I check how the lobby works on a small screen. Test the live chat before depositing: if they answer in a couple of minutes that is a good sign.

    Hope this helps someone. Set a budget and stick to it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.