How to detect if user oppened “view-source:” in browser via javascript?

本秂侑毒 提交于 2020-01-03 06:36:32

问题


Is there a way to detect if the user oppened the source code from my website via javascript?


回答1:


No there is no way. That is done through browser functionality that is outside any window that your script can access

Anything sent to the browser is easily accessed by user




回答2:


There is no JavaScript API or event which allows you to read if the user opened the page source. You could employ all kinds of workarounds, e. g. by listening to shortcuts (Chrome):

document.body.addEventListener("keydown", function(event) {
  if (event.code == "F12") {
    console.log("Developer Tools...");
  }
  if (event.getModifierState("Control")  && event.code == "KeyU") {
    console.log("View page source...");
  }
  if (event.getModifierState("Control") && event.getModifierState("Shift") && event.code == "KeyI") {
    console.log("Inspect...");
  }
});

However, it is pretty obvious that you can only capture a small fraction of all "view page source" events.




回答3:


Actually I can think of a way to do this. It might fail in some cases so you can not trust it's result to always be true but it works most of the times.

What you can do is to have a table in your database and add a row with a unique ID and the visitors IP-address each time a page is loaded. Lets say something like current time with milliseconds and some random numbers to make sure it's unique even if the visitor opens several pages at the same time. And then output the same ID to the browser as a Javascript variable and when the page loads send the ID back to the server with Ajax and when the server receives the ID it removes the row from the database. Send the ID to the server even inside an invisible Ifram to make sure server receives the ID even if Javascript is turned off in the browser. Those ID's that remain in your database are most likely those who have opened the source code of your website because both javascript and Iframe contents are disabled while viewing the source code. As I mentioned this might fail in some cases for example if the visitors internet is disconnected right when they are opening the page or if a search engine is visiting your site, but you can remove results from search engines by checking their User-Agent.



来源:https://stackoverflow.com/questions/38359657/how-to-detect-if-user-oppened-view-source-in-browser-via-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!