'2015/03/02'에 해당되는 글 2건

  1. 2015.03.02 PC 에서 모바일 페이지 접속
  2. 2015.03.02 현재 탭 jquery 하여 제어하기.

대부분의 홈페이지는 모바일 지원을 한다. 

pc에서 모바일 페이지를 보고 싶을 경우가 있는데 이럴때 사용하면 좋은 extention이 있다. 


User-Agent Switcher for Chrome

https://chrome.google.com/webstore/detail/user-agent-switcher-for-c/djflhoibgkdhkhhcedjiklpkjnoahfmg

설치를 하면 우측 상단에 browser action이 생기는데 누르면 지원하는 agent를 설정 할 수 있다. 


android , iphone 등을 선택하면 현재 browser 모드가 설정되고  google.com 에 접속하면 모바일 모드로 보이는 것을 확인 할 수 있다. 


chrome exteion을 이용한 것인데 아래 코드로 동작하는 것을 확인 하였다. 

요청 하기전 설정된 정보로 User-Agent 헤더 정보를 바꾼다. 

function updateListeners() {

if (!listener) {

listener = function(details) {

var header_map = {

requestHeaders : details.requestHeaders

};

if (details && details.url && details.requestHeaders

&& details.requestHeaders.length > 0) {

header_map = {

requestHeaders : replaceHeader(getCacheSpoofValues(

details.url, details.tabId), details.requestHeaders)

}

}

return header_map

}

}

chrome.webRequest.onBeforeSendHeaders.addListener(listener, {

"urls" : [ "http://*/*", "https://*/*" ]

}, [ "requestHeaders", "blocking" ])

}


https://developer.chrome.com/extensions/webRequest

chrome.webRequest

request 요청중의 관찰, 트래픽분석, blocking ,intercept 할 때 사용한다.

사용시 아래 권한을 준다.
      {
        "name": "My extension",
        ...
        "permissions": [
          "webRequest",
          "*://*.google.com/"
        ],
        ...
      }
      

request의 라이브사이클 onBeforeSendHeaders 2번째 단계 이다.

Life cycle of a web request from the perspective of the webrequest API

onBeforeRequest (optionally synchronous)
Fires when a request is about to occur. This event is sent before any TCP connection is made and can be used to cancel or redirect requests.
onBeforeSendHeaders (optionally synchronous)
Fires when a request is about to occur and the initial headers have been prepared. The event is intended to allow extensions to add, modify, and delete request headers (*). The onBeforeSendHeaders event is passed to all subscribers, so different subscribers may attempt to modify the request; see the Implementation details section for how this is handled. This event can be used to cancel the request.
onSendHeaders
Fires after all extensions have had a chance to modify the request headers, and presents the final (*) version. The event is triggered before the headers are sent to the network. This event is informational and handled asynchronously. It does not allow modifying or cancelling the request.
onHeadersReceived (optionally synchronous)
Fires each time that an HTTP(S) response header is received. Due to redirects and authentication requests this can happen multiple times per request. This event is intended to allow extensions to add, modify, and delete response headers, such as incoming Set-Cookie headers. The caching directives are processed before this event is triggered, so modifying headers such as Cache-Control has no influence on the browser's cache. It also allows you to redirect the request.
onAuthRequired (optionally synchronous)
Fires when a request requires authentication of the user. This event can be handled synchronously to provide authentication credentials. Note that extensions may provide invalid credentials. Take care not to enter an infinite loop by repeatedly providing invalid credentials.
onBeforeRedirect
Fires when a redirect is about to be executed. A redirection can be triggered by an HTTP response code or by an extension. This event is informational and handled asynchronously. It does not allow you to modify or cancel the request.
onResponseStarted
Fires when the first byte of the response body is received. For HTTP requests, this means that the status line and response headers are available. This event is informational and handled asynchronously. It does not allow modifying or cancelling the request.
onCompleted
Fires when a request has been processed successfully.
onErrorOccurred
Fires when a request could not be processed successfully.


'Chrome extention' 카테고리의 다른 글

현재 탭 jquery 하여 제어하기.  (0) 2015.03.02
Posted by 마법수정화살
,

https://developer.chrome.com/extensions/samples 페이지의 아래 예제를 받아서 수정.

A browser action with a popup that changes the page color


이 예제는 browser action을 클릭 했을 때 현재 탭 컨텐츠의 바탕화면 색을 변경한다. 

function click(e) {

  chrome.tabs.executeScript(null,

      {code:"document.body.style.backgroundColor='" + e.target.id + "'"});

  window.close();

}


이 것을 응용해서 편리한, 개발자도구를 못 쓰는 사용자를 위한 도구를 만들려고 했다. 

그런데 일반 java script말고 jquery를 이용해 컨텐츠를 파싱하거나 조작하려고 하였으나 잘 되지 않았다. 


아래와 같이 작성하면 jquery를 이용하여 tab의 컨텐츠를 컨트롤 할 수 있다. 

function handleClick(e) {

  chrome.tabs.executeScript(null, { file: "jquery-1.7.2.js" }, function() {

    chrome.tabs.executeScript(null,{

      code:"$('#members_scroller').css('max-height','100%');"

      });

});

  /*

  chrome.tabs.executeScript(null,

      {code:"var x = document.getElementById('members_scroller').style.maxHeight = '100%';"});

  */

}


chrome.browserAction.onClicked.addListener(handleClick);


https://developer.chrome.com/extensions/tabs#method-executeScript

executeScript

chrome.tabs.executeScript(integer tabId, object details, function callback)
- tabid가 없을경우 기본적으로 현재창의 활성화된 탭에서 실행 된다.
- 먼저 jquery 가 실행되고 callback으로 실행되는 executeScript 에서 jquery를 사용 할 수 있다.

이 기능을 사용하기 위해서는 menifest.js 에 아래 퍼미션을 추가한다. 
"permissions": [
  "activeTab"
],



'Chrome extention' 카테고리의 다른 글

PC 에서 모바일 페이지 접속  (0) 2015.03.02
Posted by 마법수정화살
,