有些时候希望对于一个常光顾的页面进行一些自动化处理。
对于一些可以写插件的浏览器来说,直接写插件可能会比较简单。
但是并不是所有的浏览器都支持插件,另外插件也不可以在不同的浏览器间共用。
这时候,js注入会是个还比较简单的办法。
既然是js注入,自然就是要在浏览器正在浏览的页面上添加一段js了。
一般这个用bookmark一个链接来实现
比如
javascript:(function(){alert(%27hello,world!%27);})();
但是每个浏览器都对可注入的js长度有一定的限制,并且要进行html转码。
所以代码比较长的话,不大可能把所有的逻辑都写在这个链接里。
最好的方法,就是动态调用服务器端的一段儿js代码(由于无法load本地的js,所以要搭建一个简单的web服务器)。
bookmark的实现
if(window.location.href.indexOf('www.iteye.com')>=0){ if(!window.pcschecker){ var uId='pcs_bk'; var st=document.getElementById(uId); if(st){st.parentNode.removeChild(st);} st=document.createElement('script'); st.src='http://localhost:8888/js?'+Math.random(); st.setAttribute('id',uId); document.getElementsByTagName('head')[0].appendChild(st); }else{window.pcschecker.check();} }else{alert('Only for PCS.')}
转码后,附带一个转码网站 http://mcdlr.com/js-inject/
javascript:(function(){if(window.location.href.indexOf(%27www.iteye.com%27)>=0){ if(!window.pcschecker){ var uId=%27pcs_bk%27; var st=document.getElementById(uId); if(st){st.parentNode.removeChild(st);} st=document.createElement(%27script%27); st.src=%27http://localhost:8888/js?%27+Math.random(); st.setAttribute(%27id%27,uId); document.getElementsByTagName(%27head%27)[0].appendChild(st); }else{window.pcschecker.check();} }else{alert(%27Only for PCS.%27)}})();
当网站是www.iteye.com并且是第一次使用时才会调入js
后台js文件
(function(w){ var pcschecker = {}; pcschecker.$=function(id){ return document.getElementById(id); } pcschecker.check = function(){ alert("hello,world!"); } w.pcschecker = pcschecker; pcschecker.check(); })(window);
附带一段简单的java的httpserver代码,由于使用了sun的实现,所以并不是所有的jdk都可以用。
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class SimpleServer { public static void main(String[] args) throws IOException { HttpServer httpServer = HttpServer.create(new InetSocketAddress(8888), 0); httpServer.setExecutor(Executors.newCachedThreadPool()); httpServer.createContext("/js", new HttpHandler() { @Override public void handle(HttpExchange httpExchange) throws IOException { InputStream fis = SimpleServer.class.getResourceAsStream("check.js"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; for (int readNum; (readNum = fis.read(buf)) != -1;) { baos.write(buf, 0, readNum); } fis.close(); byte[] bytes = baos.toByteArray(); httpExchange.sendResponseHeaders(200, bytes.length); OutputStream os = httpExchange.getResponseBody(); os.write(bytes); os.close(); } }); httpServer.start(); System.out.println("HttpServer Start!"); } }