【问题标题】:Create sidebar by manipulating the DOM of the loaded webpage通过操作加载网页的 DOM 创建侧边栏
【发布时间】:2014-10-31 04:34:33
【问题描述】:

我的简单 Chrome 扩展程序是在 document.body 的顶部注入一个 DIV,然后您可以将页面中的文本拖到扩展程序中。问题是我不希望扩展 DIV 位于顶部,而是类似于左侧的侧边栏。

换句话说,我需要知道如何以编程方式重新排列已加载的 DOM 结构,以便将所有内容移动到右侧并水平压缩,然后进一步操作可以访问左侧区域。

我正在考虑的一个选择是这样做:

tmp = document.body.innerHTML
document.body.innerHTML = '<table><tr><td id=sidebar></td><td>'
   + tmp + '</td></tr></table>'

但这将是无效的,会导致重新渲染并可能产生其他不良副作用。

顺便说一下,当前版本的扩展程序会在“加载时”注入每个页面,但这只是一个临时解决方案,单击扩展程序按钮时必须显示侧边栏。这不是这个问题的一部分,我知道该怎么做。只是为了让您知道,当用户选择单击按钮时,可以随时创建侧边栏。这就是为什么使用innerHTML 不是一个好的选择。


pageload.js

function allowDrop(ev) {ev.preventDefault()}

function drop(ev) {
    ev.preventDefault();
    var t = 'text', T = Array.prototype.slice.apply(ev.dataTransfer.types)
    if (T.indexOf('text/html') >= 0)
        t = "text/html"
    console.log('text type:', t)
    d1.innerHTML += '<div style="display:inline;border:2px solid #000000;">'+ev.dataTransfer.getData(t)+'</div> '
}

function createDragbar(id) {
    var n = document.createElement('div')
//  n.style.position = "absolute";
    n.setAttribute('id', id)
    n.style.border = '1px solid #aaaaaa'
    n.style.height = 532
    n.style.background = "teal"
    n.innerHTML = "Drop your text here "
    n.ondrop = drop
    n.ondragover = allowDrop
    document.body.insertBefore(n, document.body.firstChild)
}
createDragbar('d1')

manifest.json

{
    "name": "Yakov's Demo Extension",
    "description": "Just a demo",
    "version": "0.1",
    "permissions": [
        "activeTab"
    ],
    "content_scripts": [{
        "matches": ["http://*/*", "https://*/*", "file://*/*"],
        "js": ["pageload.js"]
    }],

    "manifest_version": 2
}

【问题讨论】:

  • 您可能应该注入一个框架以避免样式、javascript 冲突。

标签: javascript html dom google-chrome-extension


【解决方案1】:

element.insertAdjacentHTML(position, text) 呢?

https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-25
    • 2020-10-26
    • 2023-01-29
    • 2020-03-15
    • 2014-08-29
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    相关资源
    最近更新 更多