Override browser's search feature (CTRL+F), but reuse its native search field

回眸只為那壹抹淺笑 提交于 2019-12-23 18:21:25

问题


I would like to override CTRL+F in order to provide a custom search feature on a HTML page. This can easily be done with :

window.onkeydown = function(event) {
    if (event.ctrlKey && event.keyCode == 70) {
        event.preventDefault();          
        my_own_search();
    } }

but then I won't be able to use the browser's bottom native search field (example here with Firefox, French language) :

How to do a custom search feature that reuses the browser's native bottam search textbox ?

If not possible, what do you suggest for creating a custom textbox sticked at the top right (like the Search bar in Chrome) or bottom (like the Search bar in Firefox), with Bootstrap for example ?


Another example : the PDF viewer in Chrome provides custom search (=not the regular search on HTML pages, but a search adapted for PDF documents) but with the browser's native search field:


回答1:


You should NEVER be able to override a browser feature from a website. If you can, it's a major security fault in the browser.

As has been mentioned, plugins can be written for individual browsers, but they must be installed by the user (i.e. they are giving permission for your override). Otherwise you're out of luck




回答2:


I suppose because this is an old thread, but the correct answer marked here is now invalid. I have seen this on two sites in the past two days, and I kind of love it. Codepen.io for one:

Command/Control+F when in the first pane, and you will see their custom search.

If you examine their code you can see they have custom events for it, do a 'Search All Files' in chrome dev tools (CDT) for CodeMirror-search-field




回答3:


To override the search field you need to use JavaScript keycodes, using arrays like this:

// 74=j, 75=k, 78=n, 84=t,27=esc, 17=ctrl
var forbiddenCtrlKeys = new Array(74, 75, 78, 84, 123, 91, 92, 44, 165, 18, 122, 78, 27, 17, 16);
// 37=left_arrow, 39=right_arrow
var forbiddenAltKeys = new Array(37, 39, 27, 123, 91, 92, 44, 165, 18, 122, 78, 27, 17, 16);
// 8=backspace, 116=F5
var forbiddenSingleKeys = new Array(8, 116, 123, 91, 92, 44, 165, 18, 122, 78, 27, 17, 16);
// per le textbox 116=F5
var forbiddenTextBoxKeys = new Array(116, 27, 123, 91, 92, 44, 165, 18, 122, 78, 27, 17, 16);

key = window.event.keyCode; // IE

if (window.event.ctrlKey) { // CTRL
  isCtrl = true;
  isAlt = false
}

Swap the keycodes with the ones you want disabled.

A full list of keycodes can be found here.



来源:https://stackoverflow.com/questions/25997901/override-browsers-search-feature-ctrlf-but-reuse-its-native-search-field

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