开发者

How do you search for a string in a webpage with javascript?

I am making a javascript greasemonkey script that redirects you when it finds a certain string in a webpage. Here is my code:

// ==UserScript==<br>
// @name No 009 Sound System!<br>
// @version 1.0<br>
// @namespace h开发者_运维技巧ttp://www.cakeman.biz/<br>
// @description Warn user when about to view a youtube video with 009 Sound System audio<br>
// @include http://*/*<br>
// @copyright  2011+, Zack Marotta 
// ==/UserScript==

var result, search_term = 'somerandomsearchterm';
var str = document.URL;
var url_check = str.search(search_term);
if (url_check !== -1) {
var result = search_term;
alert(str);
    window.location = "http://www.web.site";
}

Nothing happens when the script runs. What did I do wrong?


For some specific functions, you have to use unsafeWindow instead of window in a Greasemonkey UserScript. If you want to get your script work at GreaseMonkey and other locations, use this:

var win = typeof unsafeWindow != "undefined" ? unsafeWindow : window;

I've shrinkened by original answer, because that seems not to be your issue. Most likely, you've forgot to add // @include to your meta block.

If your script has to redirect a certain, fixed page using GreaseMonkey, you can also shorten your scrip to:

// ==UserScript==
// @name Redirect
// @include *i-am-afraid-of-this-word*
// ==/UserScript==

location.href = "http://www.google.com/search?q=need-help-getting-courage";

For more information about the meta block, see: http://wiki.greasespot.net/Metadata_block


You notice that you're performing a Case-Sensitive search? it would not trigger if just one letter is capital when looking for a lower-case, or vice versa, if you want a case-Insensitive you need a RegExp as your "search-term".

Other thing is, you don't need <br> in the metadata block, because then the include is the one not working, otherwise the page would need to have <br> in the address to match and execute.

Extra: The !== should work just fine, but it's not needed, in this case a != would do, and it is strongly recommended that you don't use unsafeWindow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜