twitter bootstrap css clashes while in chrome extensions - google-chrome

I am using bootstrap for a chrome extension I am writing. When imported as content script the css seem to clash with alot of the sites I am viewing (even in google search result page).
Wondering if there is anything i can do to scope this to just the dom elements I inject using content script?

The solution is to use <style scoped>.
Essentially it allows you to apply a style to a DOM node and its children, but not its parent nodes. There's a nice article on CSS-Tricks explaining how to use it.
The problem is that it's not very well supported, even in Chrome, so you'll have to use a jQuery polyfill. This is basically a jQuery plugin that simulates the functionality you'd expect from <style scoped>.
Here's a working JSFiddle doing exactly that using Bootstrap.
Here's an example of how you could implement it in your extension:
content_script.js:
$.scoped(); // Initialize the plugin
...
bootstrapped = document.createElement("div");
bootstrapped.innerHTML = "<style scoped>";
bootstrapped.innerHTML += "#import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');";
bootstrapped.innerHTML += "</style>";
document.body.appendChild(bootstrapped);
...
document.body.appendChild(myDOM); // Will not possess Bootstrap styles
bootstrapped.appendChild(myDOM); // Will possess Bootstrap styles
For now, make sure to include jQuery in your page, as well as the Scoped Plugin:
"content_scripts": [ {
"js": [ "jquery.min.js", "jquery.scoped.min.js", "content_script.js" ],
"matches": [ "http://*" ]
}]

Related

Custom HTML Snippet for web components

Summary
I'm trying to figure out how to make HTML snippet with ATTRIBUTE typeahead (intellisense) as well. We have a web component and all Tags and attributes associated to tags are documented. What is the easiest way to implement this?
Example
We have a top level zing-grid tag. This tag has many attributes. For the following example I want typeahead for the caption attribute. The caption attribute should ONLY appear when I have a prefix of <zing-grid.
This issue is similar to How to insert html attribute snippet in jsx in vscode. In that example div has class intellisense. In this case I want the same typeahead implementation on my custom web component for the caption attribute.
Current POC snippet syntax
How do I make sure caption attribute is ONLY captured within the zing-grid tag
vue.code-snippets file
{
"zing-grid": {
"prefix": "<zing-grid",
"body": [
"<zing-grid \n\t$0></zing-grid>"
],
"description": "ZingGrid top level tag"
},
"zing-grid-caption": {
"prefix": "<zing-grid ",
"body": [
"<zing-grid \n\t caption=\"$1\"></zing-grid>"
],
"description": "Displays a grid with the caption attribute on the grid"
},
"caption": {
"prefix": "caption",
"body": [
"caption=\"Hello World\""
],
"description": "Displays a grid with the caption attribute on the grid"
}
}
Example Output
The following example output is from our own custom code editor implementation. We would ideally like this support for visual studio code as it is a much more powerful and complete IDE.
Cloud App Screen Recording
Another link since it is giving me trouble posting links https://duaw26jehqd4r.cloudfront.net/items/0E431n0Q1m261T3S1T03/Screen%20Recording%202019-02-07%20at%2003.35%20PM.mov?X-CloudApp-Visitor-Id=2965229
Updated
There have been new features in January 2019 documenting extended the HTML extension for users specifically for web components.
https://github.com/w3c/webcomponents/issues/776
That should lead you to their latest release in January 2019 here: https://code.visualstudio.com/updates/v1_31#_html-and-css-custom-data-support
Previous Answer
Answered by #heretic-monkey. I looked up implementing VSCode extensions and not snippets. Seems the solution is there. Clearly defined in their beginning text about the capabilities. Thanks for your time.

Is it possibile to write documentation for custom html components that gets displayed in the vscode popup when hovering the element?

Just like it happens for standard HTML elements like div I'd like to write documentation for my own custom Angular components that gets displayed when hovering them in some other template (my rer-card component for example)
I tried adding
/**
* Test!!
*/
comments almost everywhere in the component but nothing happens.
Is it possible?
v1.31 has added some functionality to custom html and css, see custom html and css data support
Today, front-end developers often code in a superset of HTML/CSS:
Web
Components allow custom HTML elements such as .
PostCSS allows custom CSS properties such
as size and not-yet-standardized CSS features such as :any-link.
Various frameworks allow even greater flexibility in the source
HTML/CSS.
In this iteration, we improved the HTML custom data support
introduced in 1.30 and added CSS custom data support. Use
html.experimental.customData or css.experimental.customData to load
custom data. (html.experimental.custom.tags and
html.experimental.custom.attributes are removed.) Alternatively,
bundle the JSON into an extension with
contributes.html.experimental.customData or
contributes.css.experimental.customData.
Finally, if you are writing a
Language Server that uses vscode-html-languageservice or
vscode-css-languageservice, you can create the Language Service with
custom data. Custom data enhances VS Code's understanding of HTML/CSS.
For example, with these HTML/CSS JSON contributions, VS Code could
provide completion and hover for the custom HTML tag/attribute and CSS
property/pseudoClass:
{
"version": 1,
"tags": [{
"name": "my-button",
"description": "My button",
"attributes": [{
"name": "type",
"description": "My button type",
"values": [
{ "name": "alert" }
]
}]
}]
}
{
"version": 1,
"properties": [{
"name": "my-size",
"description": "Compiles down to `width` and `height`. See details at https://github.com/postcss/postcss-size."
}],
"pseudoClasses": [{
"name": ":my-link",
"description": ":any-link pseudo class. See details at https://preset-env.cssdb.org/features#any-link-pseudo-class."
}]
}
See the link at the top of this answer for more links on how to use this functionality.

How do I use Web Component Shards?

There's a new project for, what it seems to me to be, a way to vulcanise elements in bundles, web-components-shards.
I'm interested in the gulp version, gulp-web-components-shards.
Both projects lack comprehensive instructions in the README, how the file structure should be, what the output should look like and how to use it, or how I can declare which elements are shared between bundles.
Considering this use case:
A sample File Structure
The Polymer elements
./app/elements
shared-element-1/shared-element-1.html
shared-element-2/shared-element-2.html
homepage-element-1/homepage-element-1.html
homepage-element-2/homepage-element-2.html
contact-element-1/contact-element-2.html
contact-element-1/contact-element-2.html
Note: shared-element-1.html & shared-element-2 are used in all routes
The routes:
./app/homepage.jade
./app/contact.jade
How should I set-up my gulp task so that is splits bundles I can use like so:
/* homepage.jade */
link(rel='import', href='/dist/shared-elements/shared-elements.html')
link(rel='import', href='/dist/homepage-elements/homepage-elements.html')
/* contact.jade */
link(rel='import', href='/dist/shared-elements/shared-elements.html')
link(rel='import', href='/dist/contact-elements/contact-elements.html')
Note: I've already opened an Issue - Still I think it would be nice to have an example usage snippet/explanation here as well.
In that web-component-shards seems to be a deprecated/abandoned, I'd take a look at Polymer CLI where this is a little more laid out in the documentation available: https://www.polymer-project.org/1.0/docs/tools/polymer-cli#app It allows us to structure the build of our app in a polymer.json files shaped like:
{
"entrypoint": "index.html",
"shell": "src/app-shell/app-shell.html",
"fragments": [
"src/view-one/view-one.html",
"src/view-one/view-two.html"
],
"sources": [
"src/**/*",
"images/**/*",
"bower.json"
],
"includeDependencies": [
"bower_components/webcomponentsjs/webcomponents-lite.min.js"
]
}
For you the most important parts would be the "fragments" as it would structure most closely to the app you've described. Then you could use the hooks specifically set up in the CLI to process your JADE and what not as well.

Chrome extension to make a small CSS change to *.google.com

I just wrote a simple extension that has permission to *.google.com and changes some CSS on one class, and I think I overlooked something simple. I'm changing the +1 button, which is implemented like so:
<button ... class="esw eswd BRowJd Jt">
In my style.css I say:
button.eswa { border: 2px solid #000000; }
the change never appears. I also tried switching the class to Jt in case that was overriding my CSS, no luck. The class that defines the unclicked +1 button is the "eswa", fyi.
As per the documentation I also set permissions to the sites I want to alter in my manifest.json
{
"name": "G+ Rebrander",
"version": "0.92",
"description": "Returns the original branding for G+ (pre March 2012) such as the +1 button.",
"browser_action": {
"default_icon": "g-plus.png"
},
"icons":{
"128":"g-plus128.png"
},
"permissions": [
"http://plus.google.com/",
"https://plus.google.com/",
"http://*.google.com/",
"https://*.google.com/",
"tabs"
]
}
In the future listing your whole manifest.json file would be extremely helpful, since your didnt its hard for me to know exactly what your doing and thus what your error could be....so Ill just list a few possibilities.
Using !important in your css rule is always a good idea when overriding css.
Permissions is for if your injecting code from say the background page, not content scripts that get automatically added. The docs are slightly vague on that.
For content scripts that get added automatically you only need to set the matches field of the content script.
Your matches dont have a * at the end of them and as such would only match the front page and not any search results, which is what I assume your targeting.
Keep in mind that google will typically redirect to a server in your country, so for me going to www.google.com will be redirected to www.google.com.au.
The unlicked +1 for me was ewsd, not ewsa.
If your only injecting css and not a script aswell then its a good idea to use the run_at field with a value of document_start. This will make sure your css is applied before the page is visible and thus avoid the page changing later when it gets applied. If you use this then you must use !important or the css added by the page later will override your css rule.
So with all that a working manifest and css file looks like this.....
manifest.json
{
"name": "css rules",
"content_scripts": [
{
"matches": [
"*://*.google.com/*",
"*://*.google.com.au/*"
],
"css": ["new.css"],
"run_at" : "document_start"
}
],
"version":"1.0"
}
new.css
button.eswd { border: 2px solid #000000 !important;}
Set !important on the element to overwrite Google's style.

Can I create links with 'target="_blank"' in Markdown?

Is there a way to create a link in Markdown that opens in a new window? If not, what syntax do you recommend to do this? I'll add it to the markdown compiler I use. I think it should be an option.
As far as the Markdown syntax is concerned, if you want to get that detailed, you'll just have to use HTML.
Hello, world!
Most Markdown engines I've seen allow plain old HTML, just for situations like this where a generic text markup system just won't cut it. (The StackOverflow engine, for example.) They then run the entire output through an HTML whitelist filter, regardless, since even a Markdown-only document can easily contain XSS attacks. As such, if you or your users want to create _blank links, then they probably still can.
If that's a feature you're going to be using often, it might make sense to create your own syntax, but it's generally not a vital feature. If I want to launch that link in a new window, I'll ctrl-click it myself, thanks.
Kramdown supports it. It's compatible with standard Markdown syntax, but has many extensions, too. You would use it like this:
[link](url){:target="_blank"}
I don't think there is a markdown feature, although there may be other options available if you want to open links which point outside your own site automatically with JavaScript.
Array.from(javascript.links)
.filter(link => link.hostname != window.location.hostname)
.forEach(link => link.target = '_blank');
jsFiddle.
If you're using jQuery:
$(document.links).filter(function() {
return this.hostname != window.location.hostname;
}).attr('target', '_blank');
jsFiddle.
With Markdown v2.5.2, you can use this:
[link](URL){:target="_blank"}
So, it isn't quite true that you cannot add link attributes to a Markdown URL. To add attributes, check with the underlying markdown parser being used and what their extensions are.
In particular, pandoc has an extension to enable link_attributes, which allow markup in the link. e.g.
[Hello, world!](http://example.com/){target="_blank"}
For those coming from R (e.g. using rmarkdown, bookdown, blogdown and so on), this is the syntax you want.
For those not using R, you may need to enable the extension in the call to pandoc with +link_attributes
Note: This is different than the kramdown parser's support, which is one the accepted answers above. In particular, note that kramdown differs from pandoc since it requires a colon -- : -- at the start of the curly brackets -- {}, e.g.
[link](http://example.com){:hreflang="de"}
In particular:
# Pandoc
{ attribute1="value1" attribute2="value2"}
# Kramdown
{: attribute1="value1" attribute2="value2"}
^
^ Colon
One global solution is to put <base target="_blank">
into your page's <head> element. That effectively adds a default target to every anchor element. I use markdown to create content on my Wordpress-based web site, and my theme customizer will let me inject that code into the top of every page. If your theme doesn't do that, there's a plug-in
Not a direct answer, but may help some people ending up here.
If you are using GatsbyJS there is a plugin that automatically adds target="_blank" to external links in your markdown.
It's called gatsby-remark-external-links and is used like so:
yarn add gatsby-remark-external-links
plugins: [
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [{
resolve: "gatsby-remark-external-links",
options: {
target: "_blank",
rel: "noopener noreferrer"
}
}]
}
},
It also takes care of the rel="noopener noreferrer".
Reference the docs if you need more options.
For ghost markdown use:
[Google](https://google.com" target="_blank)
Found it here:
https://cmatskas.com/open-external-links-in-a-new-window-ghost/
I'm using Grav CMS and this works perfectly:
Body/Content:
Some text[1]
Body/Reference:
[1]: http://somelink.com/?target=_blank
Just make sure that the target attribute is passed first, if there are additional attributes in the link, copy/paste them to the end of the reference URL.
Also work as direct link:
[Go to this page](http://somelink.com/?target=_blank)
You can do this via native javascript code like so:
var pattern = /a href=/g;
var sanitizedMarkDownText = rawMarkDownText.replace(pattern,"a target='_blank' href=");
JSFiddle Code
In my project I'm doing this and it works fine:
[Link](https://example.org/ "title" target="_blank")
Link
But not all parsers let you do that.
There's no easy way to do it, and like #alex has noted you'll need to use JavaScript. His answer is the best solution but in order to optimize it, you might want to filter only to the post-content links.
<script>
var links = document.querySelectorAll( '.post-content a' );
for (var i = 0, length = links.length; i < length; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
</script>
The code is compatible with IE8+ and you can add it to the bottom of your page. Note that you'll need to change the ".post-content a" to the class that you're using for your posts.
As seen here: http://blog.hubii.com/target-_blank-for-links-on-ghost/
If someone is looking for a global rmarkdown (pandoc) solution.
Using Pandoc Lua Filter
You could write your own Pandoc Lua Filter which adds target="_blank" to all links:
Write a Pandoc Lua Filter, name it for example links.lua
function Link(element)
if
string.sub(element.target, 1, 1) ~= "#"
then
element.attributes.target = "_blank"
end
return element
end
Then update your _output.yml
bookdown::gitbook:
pandoc_args:
- --lua-filter=links.lua
Inject <base target="_blank"> in Header
An alternative solution would be to inject <base target="_blank"> in the HTML head section using the includes option:
Create a new HTML file, name it for example links.html
<base target="_blank">
Then update your _output.yml
bookdown::gitbook:
includes:
in_header: links.html
Note: This solution may also open new tabs for hash (#) pointers/URLs. I have not tested this solution with such URLs.
In Laravel I solved it this way:
$post->text= Str::replace('<a ', '<a target="_blank"', $post->text);
Not works for a specific link. Edit all links in the Markdown text. (In my case it's fine)
I ran into this problem when trying to implement markdown using PHP.
Since the user generated links created with markdown need to open in a new tab but site links need to stay in tab I changed markdown to only generate links that open in a new tab. So not all links on the page link out, just the ones that use markdown.
In markdown I changed all the link output to be <a target='_blank' href="..."> which was easy enough using find/replace.
I do not agree that it's a better user experience to stay within one browser tab. If you want people to stay on your site, or come back to finish reading that article, send them off in a new tab.
Building on #davidmorrow's answer, throw this javascript into your site and turn just external links into links with target=_blank:
<script type="text/javascript" charset="utf-8">
// Creating custom :external selector
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/)
&& (obj.hostname != location.hostname);
};
$(function(){
// Add 'external' CSS class to all external links
$('a:external').addClass('external');
// turn target into target=_blank for elements w external class
$(".external").attr('target','_blank');
})
</script>
You can add any attributes using {[attr]="[prop]"}
For example [Google] (http://www.google.com){target="_blank"}
For completed alex answered (Dec 13 '10)
A more smart injection target could be done with this code :
/*
* For all links in the current page...
*/
$(document.links).filter(function() {
/*
* ...keep them without `target` already setted...
*/
return !this.target;
}).filter(function() {
/*
* ...and keep them are not on current domain...
*/
return this.hostname !== window.location.hostname ||
/*
* ...or are not a web file (.pdf, .jpg, .png, .js, .mp4, etc.).
*/
/\.(?!html?|php3?|aspx?)([a-z]{0,3}|[a-zt]{0,4})$/.test(this.pathname);
/*
* For all link kept, add the `target="_blank"` attribute.
*/
}).attr('target', '_blank');
You could change the regexp exceptions with adding more extension in (?!html?|php3?|aspx?) group construct (understand this regexp here: https://regex101.com/r/sE6gT9/3).
and for a without jQuery version, check code below:
var links = document.links;
for (var i = 0; i < links.length; i++) {
if (!links[i].target) {
if (
links[i].hostname !== window.location.hostname ||
/\.(?!html?)([a-z]{0,3}|[a-zt]{0,4})$/.test(links[i].pathname)
) {
links[i].target = '_blank';
}
}
}
Automated for external links only, using GNU sed & make
If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed command once the (X)HTML has been created from Markdown:
sed -i 's|href="http|target="_blank" href="http|g' index.html
This can be further automated by adding above sed command to a makefile. For details, see GNU make or see how I have done that on my website.
If you just want to do this in a specific link, just use the inline attribute list syntax as others have answered, or just use HTML.
If you want to do this in all generated <a> tags, depends on your Markdown compiler, maybe you need an extension of it.
I am doing this for my blog these days, which is generated by pelican, which use Python-Markdown. And I found an extension for Python-Markdown Phuker/markdown_link_attr_modifier, it works well. Note that an old extension called newtab seems not work in Python-Markdown 3.x.
For React + Markdown environment:
I created a reusable component:
export type TargetBlankLinkProps = {
label?: string;
href?: string;
};
export const TargetBlankLink = ({
label = "",
href = "",
}: TargetBlankLinkProps) => (
<a href={href} target="__blank">
{label}
</a>
);
And I use it wherever I need a link that open in a new window.
For "markdown-to-jsx" with MUI v5
This seem to work for me:
import Markdown from 'markdown-to-jsx';
...
const MarkdownLink = ({ children, ...props }) => (
<Link {...props}>{children}</Link>
);
...
<Markdown
options={{
forceBlock: true,
overrides: {
a: {
component: MarkdownLink,
props: {
target: '_blank',
},
},
},
}}
>
{description}
</Markdown>
This works for me: [Page Link](your url here "(target|_blank)")