Chrome extension inject sidebar into page

前端 未结 4 1184
难免孤独
难免孤独 2020-12-07 23:41

I would like my chrome extension to be able to inject a 300px sidebar on the right side of any page when it is activated. I am looking for the best way to constrain the ent

4条回答
  •  悲哀的现实
    2020-12-08 00:07

    Update

    For anyone googling, overhauled this to reflect what I'm actually using in an app, use jQuery, have more safeguards, and be more respectful of current page css.

    //height of top bar, or width in your case
    var height = '30px';
    
    //resolve html tag, which is more dominant than 
      var html;
      if (document.documentElement) {
        html = $(document.documentElement); //just drop $ wrapper if no jQuery
      } else if (document.getElementsByTagName('html') && document.getElementsByTagName('html')[0]) {
        html = $(document.getElementsByTagName('html')[0]);
      } else if ($('html').length > -1) {//drop this branch if no jQuery
        html = $('html');
      } else {
        alert('no html tag retrieved...!');
        throw 'no html tag retrieved son.';
      }
    
    //position
    if (html.css('position') === 'static') { //or //or getComputedStyle(html).position
      html.css('position', 'relative');//or use .style or setAttribute
    }
    
    //top (or right, left, or bottom) offset
    var currentTop = html.css('top');//or getComputedStyle(html).top
    if (currentTop === 'auto') {
      currentTop = 0;
    } else {
      currentTop = parseFloat($('html').css('top')); //parseFloat removes any 'px' and returns a number type
    }
    html.css(
      'top',     //make sure we're -adding- to any existing values
      currentTop + parseFloat(height) + 'px'
    );
    

    You're almost done. You've styled the page html. You might have noticed css from the page affects your stuff to. You can resolve this by containing it within an iframe:

    var iframeId = 'someSidebar';
    if (document.getElementById(iframeId)) {
      alert('id:' + iframeId + 'taken please dont use this id!');
      throw 'id:' + iframeId + 'taken please dont use this id!';
    }
    html.append(
      ''
    );
    document.getElementById(iframeId).contentDocument.body.innerHTML =
      '                \
      

    UNSTYLED HTML!

    ';

    Yes, you have to append the iframe before setting the innerHTML

    You should be able to copy/paste and edit this and be one your way!

提交回复
热议问题