Back when bitcoin was young you could mine in a web browser. There were also snippets of code you could insert into your website (header I think) that would mine for you when people had those websites open. It didn't take off because the difficulty started to rise, but at least for a short while it was hot.
I don't think it would work today under your proposed model unless you could prevent others from hijacking your code and redirecting the hashrate somewhere else. Unless of course these were websites under your control.
I remember this as well, and there was also a phase where it was popular with Litecoin with Litecoinpool integrating a now deprecated Java-based LTC miner into a webpage (it's still there, just search- one of my first posts was about this!). It's still possible to do this today with an Altcoin of some sort, whether it's in plain sight or not. I'd imagine it'd take a few lines of code changed and optimizations to hashing algorithms, etc but it's definitely possible. As long as it's for good intent.