If you want to keep it as a simple, client-side only widget, the simple answer is you can't do it exactly like you describe.
The two solutions that come to mind for this are as follows, the first being a compromise but simple and the second being a bit more involved (for both you and users of your widget).
Referer Check
You could validate the referer HTTP header to check that the domain matches the one expected for the particular Site ID, but keep in mind that not all browsers will send this (and most will not if the referring page is HTTPS) and that some browser privacy plugins can be configured to withhold it, in which case your widget would not work or you would need an extra, clunky, step in the user experience.
- Website
www.foo.com
embeds your widget using say an embedded script<script src="//example.com/widget.js?siteId=1234&pageId=456"></script>
- Your widget uses server side code to generate the .js file dynamically (e.g. the request for the .js file could follow a rewrite rule on your server to map to a PHP / ASPX).
- The server side code checks the
referer
HTTP header to see if it matches the expected value in your database. - On match the widget runs as normal.
- On mismatch, or if the referer is blank/missing, the widget will still run, but there will be an extra step that asks the user to confirm that they have accessed the widget from
www.foo.com
- In order for the confirmation to be safe from clickjacking, you must open the confirmation step in a popup window.
Server Check
Could be a bit over engineered for your purposes and runs the risk of becoming too complicated for clients who wish to embed your widget - you decide.
- Website
www.foo.com
wants to embed your widget for the current page request it is receiving from a user. - The
www.foo.com
server makes an API request (passing a secret key) to an API you host, requesting a one time key for Page ID 456. - Your API validates the secret key, generates a secure one time key and passes back a value whilst recording the request in the database.
www.foo.com
embeds the script as follows<script src="//example.com/widget.js?siteId=1234&oneTimeKey=231231232132197"></script>
- Your widget uses server side code to generate the js file dynamically (e.g. the .js could follow a rewrite rule on your server to map to a PHP / ASPX).
- The server side code checks the
oneTimeKey
andsiteId
combination to check it is valid, and if so generates the widget code and deletes the database record. - If the user reloads the page the above steps would be repeated and a new one time key would be generated. This would guard against
evil.com
from page scraping the embed code and parameters.