javascript - unwrap() removes link in jsFiddle test, but not in Tampermonkey script? -
i tried remove link on div, , works using unwrap()
, see on jsfiddle
now, want implement userscript remove link on website (example on jsfiddle), it's not working.
i'm using tampermonkey. here's userscript:
// ==userscript== // @name remove link // @include http://jsfiddle.net/dv3fm/2/embedded/result/ // ==/userscript== function addjquery(callback) { var script = document.createelement("script"); script.setattribute("src", "http://code.jquery.com/jquery-1.9.1.js"); script.addeventlistener('load', function() { var script = document.createelement("script"); script.textcontent = "(" + callback.tostring() + ")();"; document.body.appendchild(script); }, false); document.body.appendchild(script); } // guts of userscript function main() { $('.spoiler > .smallfont').unwrap(); } // load jquery , execute main function addjquery(main);
here's html:
<div class="spoiler"> <!--i want remove link --> <a href="http://www.domain.com" target="_blank"> <div class="smallfont" id="bbcode_div"/> </div> </a> </div> <!--i want result such : --> <div class="spoiler"> <div class="smallfont" id="bbcode_div"/> </div> </div>
what userscript doing wrong? how can remove link using unwrap jquery in userscript?
there 2 problems script:
- it's including wrong page.
- it's injecting jquery conflicts page's own jquery.
(1) jsfiddle loads payload page in iframes. fiddle of:
http://jsfiddle.net/dv3fm/2/
the content iframe (current scheme):
http://fiddle.jshell.net/dv3fm/2/show/light/
so, script must include iframe content wants change.
(2) target page has jquery, using addjquery()
bust either page's jquery or script's jquery, depending on timing.
as general rule, never use script injection (create <script>
tag), if can it!
fortunately, tampermonkey, , greasemonkey provide far-superior option in form of the @require
directive.
with (and @grant
directive), script can avoid conflicts page's script (and can run, in greasemonkey, if page's js blocked).
given that, script become:
// ==userscript== // @name remove link // @include http://fiddle.jshell.net/dv3fm/2/show/light/ // @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js // @grant gm_addstyle // ==/userscript== /*- @grant directive needed work around design change introduced in gm 1.0. restores sandbox. */ $('.spoiler > .smallfont').unwrap();
if want script able work in browsers don't support @require
directive, without losing advantages in browsers do, use second technique shown in this answer.
but recommend sticking tampermonkey , greasemonkey (which code compatible).
Comments
Post a Comment